Sources/OrgApp/DocumentSession.swift

9945f06859a5feee9b6af3496e944cb6b395715b
orgstar/Sources/OrgApp/DocumentSession.swift

1473 lines · 75100 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 the app, as Emacs's buffers: each keeps its text, caret, undo and
  46/// unsaved edits while another is shown. Buffers show in panes (`EditorPane`), one or more
  47/// per window; `focused` is the pane commands and menus act on, and the properties below
  48/// that describe one buffer (`path`, `outline`, `isDirty`, `conflict`, `revealRequest`) are
  49/// its. The view layer attaches an editor to each buffer and, per pane, follows the pane's
  50/// `path` and `revealRequest`.
  51@MainActor
  52@Observable
  53public final class DocumentSession {
  54    /// Where buffers show. There is always at least one.
  55    public private(set) var panes: [EditorPane]
  56    /// The pane with focus: what `open`, `reveal`, saving and the forwarders below act on.
  57    public var focused: EditorPane
  58    /// The focused pane's file.
  59    public var path: String? { focused.path }
  60    /// The focused pane's buffer state. Not observed: it changes on every keystroke; views
  61    /// follow `path`, `isDirty` and `outline`.
  62    public var document: DocumentState? { current?.buffer.document }
  63    public var outline: [OutlineEntry] { focused.outline }
  64    /// Bumped when the focused buffer settles after edits, and when a file opens: views that
  65    /// read `document` follow this.
  66    public var editVersion: Int { focused.editVersion }
  67    public var isDirty: Bool { focused.isDirty }
  68    /// The file isn't UTF-8, so it can't be edited or saved.
  69    public var isReadOnly: Bool { focused.isReadOnly }
  70    /// Set while the focused buffer and the file on disk conflict; says how to resolve it.
  71    public var conflict: String? { focused.conflict }
  72    /// Bumped to ask the focused pane's editor to reveal an offset.
  73    public var revealRequest: (offset: Int, id: Int)? { focused.revealRequest }
  74    /// Open files, in the order buffers were opened (each after the one focused then).
  75    public private(set) var openPaths: [String] = []
  76    /// Open files with unsaved edits.
  77    public private(set) var dirtyPaths: Set<String> = []
  78    public var lastError: String? { didSet { lastErrorTitle = nil } }
  79    /// What failed, as the title of the alert that shows `lastError`; nil when `lastError` was
  80    /// set without one.
  81    public private(set) var lastErrorTitle: String?
  82
  83    /// Sets `lastError` to `message` under `title`, which says what failed ("Couldn't Save File").
  84    public func showError(_ title: String, _ message: String) {
  85        lastError = message
  86        lastErrorTitle = title
  87    }
  88
  89    public var saveMode: SaveMode = .automatic
  90    public var autosaveDelay: Duration = .seconds(1)
  91    /// Org options for commands the session runs (refile, archive).
  92    public var options: EditingOptions = .org
  93    /// Called with a file's path after its text changed through the session, typed or not.
  94    @ObservationIgnored public var textChanged: ((String) -> Void)?
  95    /// Called with a file's path each time a save wrote it to disk.
  96    @ObservationIgnored public var fileWritten: ((String) -> Void)?
  97    /// TODO keywords and priorities for files without their own settings.
  98    public var defaults: OrgSettings = .default
  99
 100    /// A buffer for `bytes` read from `path`, with the keywords of the setup files it names.
 101    func loaded(_ bytes: [UInt8], path: String) -> DocumentState {
 102        DocumentState(bytes: bytes, defaults: defaults.resolvingSetupFiles(in: SourceText(bytes: bytes).text, path: path, read: readText))
 103    }
 104
 105    /// A file's text, for setup files.
 106    func readText(_ file: String) -> String? {
 107        (try? fileSystem.read(URL(fileURLWithPath: file))).flatMap { $0 }.flatMap { String(bytes: $0, encoding: .utf8) }
 108    }
 109
 110    /// C-c C-c on a keyword line: the open file's setup files read again (`org-mode-restart`).
 111    public func refreshSetup() {
 112        guard let entry = current else { return }
 113        resolveSetup(entry)
 114        for pane in panes(showing: entry.path) {
 115            refresh(pane)
 116            pane.editVersion += 1
 117        }
 118    }
 119
 120    /// The entry's setup files read again, as its text names them now.
 121    private func resolveSetup(_ entry: Entry) {
 122        let settings = defaults.resolvingSetupFiles(in: entry.buffer.document.text, path: entry.path, read: readText)
 123        if settings != entry.buffer.document.defaults { entry.buffer.update { $0.setDefaults(settings) } }
 124    }
 125
 126    /// One open file.
 127    @MainActor
 128    final class Entry {
 129        let path: String
 130        var buffer: DocumentBuffer
 131        var conflict: String?
 132        var autosave: Task<Void, Never>?
 133
 134        init(path: String, buffer: DocumentBuffer) {
 135            self.path = path
 136            self.buffer = buffer
 137        }
 138    }
 139
 140    /// Files and recovery through `crypt`, and as they are on disk.
 141    private let fileSystem: FileSystem
 142    private let recovery: RecoveryStore
 143    private let diskFileSystem: FileSystem
 144    private let diskRecovery: RecoveryStore
 145    /// Passphrases and encrypted entries of the open files.
 146    @ObservationIgnored public let crypt = CryptVault()
 147    @ObservationIgnored private var entries: [Entry] = []
 148    /// The focused pane's buffer.
 149    private var current: Entry? { focused.path.flatMap(entry) }
 150    /// Paths, most recently shown first, across every pane.
 151    @ObservationIgnored private var history: [String] = []
 152    @ObservationIgnored private var outlineUpdates: [String: Task<Void, Never>] = [:]
 153    private var requestID = 0
 154
 155    public init(
 156        fileSystem: FileSystem = CoordinatedFileSystem(),
 157        recovery: RecoveryStore = FileRecoveryStore(directory: WorkspaceModel.defaultDirectory.appendingPathComponent("Recovery"))
 158    ) {
 159        diskFileSystem = fileSystem
 160        diskRecovery = recovery
 161        self.fileSystem = CryptFileSystem(base: fileSystem, vault: crypt)
 162        self.recovery = CryptRecoveryStore(base: recovery, vault: crypt)
 163        let pane = EditorPane()
 164        panes = [pane]
 165        focused = pane
 166    }
 167
 168    // MARK: - Encryption
 169
 170    /// `org-crypt-use-before-save-magic`: entries with `cryptTag` are encrypted on every save.
 171    public var encryptsTaggedEntries: Bool {
 172        get { crypt.encryptsTaggedEntries }
 173        set { crypt.encryptsTaggedEntries = newValue }
 174    }
 175
 176    /// `org-crypt-tag-matcher`.
 177    public var cryptTag: String {
 178        get { crypt.tag }
 179        set { crypt.tag = newValue }
 180    }
 181
 182    /// Open files that aren't saved until a passphrase is given: tagged entries that would be
 183    /// written unencrypted, or an encrypted file without one. Other edits to them wait too.
 184    public private(set) var held: [String: CryptHold] = [:]
 185
 186    /// An encrypted file waiting for its passphrase to open, and the pane to show it in.
 187    public private(set) var unlockRequest: String?
 188    @ObservationIgnored private var unlockPane: EditorPane?
 189
 190    /// The passphrase remembered in the Keychain, after Touch ID, Face ID or the device's
 191    /// password; nil when there's none or it wasn't given.
 192    @ObservationIgnored public var storedPassphrase: (String) async -> String? = { await CryptPassphrases.stored(for: $0) }
 193    @ObservationIgnored public var hasStoredPassphrase: (String) -> Bool = { CryptPassphrases.hasStored($0) }
 194    /// Files whose remembered passphrase is being asked for, and those where it was refused:
 195    /// the Keychain is asked once per file until the file closes or Encrypt is chosen.
 196    @ObservationIgnored private var askingKeychain: Set<String> = []
 197    @ObservationIgnored private var refusedKeychain: Set<String> = []
 198
 199    public static func isEncryptedFile(_ path: String) -> Bool { CryptVault.isEncryptedFile(path) }
 200
 201    /// An encrypted org file, which lists with the org files.
 202    public static func isEncryptedOrgFile(_ path: String) -> Bool { path.hasSuffix(".org.gpg") }
 203
 204    /// Gives `passphrase` for `path`: an encrypted file opens with it, and a held file is saved.
 205    /// It must open the file, or the file's encrypted entries if it has any. A message when it
 206    /// doesn't.
 207    public func unlock(_ passphrase: String, for path: String) -> String? {
 208        if let entry = entry(path) {
 209            if let message = OrgCrypt.firstMessage(entry.buffer.document.text), !OrgCrypt.opens(message, passphrase: passphrase) {
 210                return String(localized: "Wrong passphrase")
 211            }
 212            // An encrypted file on disk keeps its passphrase: a passphrase given after Forget
 213            // must open it.
 214            if Self.isEncryptedFile(entry.path), let disk = try? diskFileSystem.read(URL(fileURLWithPath: entry.path)),
 215               !CryptVault.opens(disk, passphrase: passphrase) {
 216                return String(localized: "Wrong passphrase")
 217            }
 218            crypt.unlock(passphrase, for: entry.path)
 219            refusedKeychain.remove(entry.path)
 220            save(entry)
 221            return nil
 222        }
 223        guard Self.isEncryptedFile(path) else { return nil }
 224        let bytes: [UInt8]
 225        do {
 226            guard let read = try diskFileSystem.read(URL(fileURLWithPath: path)) else { return "\((path as NSString).lastPathComponent) no longer exists." }
 227            bytes = read
 228        } catch {
 229            return error.localizedDescription
 230        }
 231        guard CryptVault.opens(bytes, passphrase: passphrase) else { return String(localized: "Wrong passphrase") }
 232        crypt.unlock(passphrase, for: path)
 233        let pane = unlockPane.flatMap { pane in panes.contains { $0 === pane } ? pane : nil } ?? focused
 234        unlockRequest = nil
 235        unlockPane = nil
 236        open(path, in: pane)
 237        return nil
 238    }
 239
 240    /// The encrypted file waiting for its passphrase stays closed.
 241    public func cancelUnlock() {
 242        unlockRequest = nil
 243        unlockPane = nil
 244    }
 245
 246    /// A crypt command used `passphrase` for `path`: saves use it from now on, without asking.
 247    public func cryptUsed(_ passphrase: String, for path: String) {
 248        crypt.unlock(passphrase, for: path)
 249        refusedKeychain.remove(path)
 250    }
 251
 252    /// The entry holding `plaintext` in `path`'s buffer was decrypted from `message`.
 253    public func cryptDecrypted(message: String, plaintext: String, for path: String) {
 254        crypt.remember(message: message, plaintext: plaintext, for: path)
 255    }
 256
 257    /// Forget Encryption Passphrase: the passphrase leaves the Keychain and the session.
 258    public func forgetPassphrase(for path: String) {
 259        CryptPassphrases.forget(path)
 260        crypt.forgetPassphrase(for: path)
 261    }
 262
 263    /// `title`, of the heading at `heading` in `path`, as it may be shown and kept outside
 264    /// the editor (the clock's file, widgets, the Live Activity, the menu bar): a placeholder
 265    /// for a heading of an encrypted file or one inside an entry that's encrypted on disk.
 266    public func shareableTitle(_ title: String, path: String, heading: Int) -> String {
 267        let hidden = Self.isEncryptedFile(path)
 268            || (crypt.sealsEntries(for: path) && document(of: path).map { OrgCrypt.isInTaggedText($0.text, at: heading, tag: cryptTag) } == true)
 269        return hidden ? String(localized: "Encrypted entry") : title
 270    }
 271
 272    /// Why a copy of the buffer can't be kept, with what to do; the buffer's notice shows.
 273    private func keepFailure(_ hold: CryptHold) -> String {
 274        if let current { _ = updateHold(current) }
 275        return hold.localizedDescription + ". " + String(localized: "Give the passphrase with Encrypt… first, so that a copy of your edits can be kept encrypted.")
 276    }
 277
 278    /// Whether `path`'s buffer is held back from disk now.
 279    private func updateHold(_ entry: Entry) -> CryptHold? {
 280        let hold = entry.buffer.document.isDirty ? crypt.hold(entry.buffer.document.text, for: entry.path) : nil
 281        if held[entry.path] != hold { held[entry.path] = hold }
 282        return hold
 283    }
 284
 285    /// Asks the Keychain for `entry`'s passphrase, once, and saves with it.
 286    private func askKeychain(_ entry: Entry) {
 287        let path = entry.path
 288        guard !askingKeychain.contains(path), !refusedKeychain.contains(path), hasStoredPassphrase(path) else { return }
 289        askingKeychain.insert(path)
 290        Task { [weak self, weak entry] in
 291            guard let self else { return }
 292            let passphrase = await self.storedPassphrase(path)
 293            self.askingKeychain.remove(path)
 294            guard let entry, self.entries.contains(where: { $0 === entry }) else { return }
 295            if let passphrase, self.unlock(passphrase, for: path) == nil { return }
 296            self.refusedKeychain.insert(path)
 297        }
 298    }
 299
 300    // MARK: - Panes
 301
 302    /// A new, empty pane.
 303    public func makePane() -> EditorPane {
 304        let pane = EditorPane()
 305        panes.append(pane)
 306        return pane
 307    }
 308
 309    /// Removes `pane`; its buffers stay open. The last pane stays.
 310    public func closePane(_ pane: EditorPane) {
 311        guard panes.count > 1, let index = panes.firstIndex(where: { $0 === pane }) else { return }
 312        panes.remove(at: index)
 313        if focused === pane { focused = panes[0] }
 314    }
 315
 316    /// The panes showing `path`.
 317    private func panes(showing path: String) -> [EditorPane] {
 318        panes.filter { $0.path == path }
 319    }
 320
 321    private var buffer: DocumentBuffer? { current?.buffer }
 322    /// The focused buffer's pending autosave, for tests to wait on.
 323    var autosave: Task<Void, Never>? { current?.autosave }
 324    private var url: URL? { path.map { URL(fileURLWithPath: $0) } }
 325    /// Whether the open file is an org file (`.org`, `.org_archive`), not plain text.
 326    public var isOrg: Bool { path.map(Self.isOrgPath) ?? false }
 327
 328    public static func isOrgPath(_ path: String) -> Bool {
 329        path.hasSuffix(".org") || path.hasSuffix(".org_archive") || path.hasSuffix(".org.gpg")
 330    }
 331
 332    /// The caret in the open file.
 333    public var caret: Int { buffer?.selection.first?.lowerBound ?? 0 }
 334    private var name: String { path.map { ($0 as NSString).lastPathComponent } ?? "" }
 335
 336    /// The open buffer of `path`, or of the same file by another path (`find-buffer-visiting`
 337    /// by truename).
 338    private func entry(_ path: String) -> Entry? {
 339        if let exact = entries.first(where: { $0.path == path }) { return exact }
 340        let truename = URL(fileURLWithPath: path).resolvingSymlinksInPath().path
 341        return entries.first { URL(fileURLWithPath: $0.path).resolvingSymlinksInPath().path == truename }
 342    }
 343
 344    /// The text of `path`: its buffer's when it's open, else what's on disk.
 345    public func text(of path: String) -> String? {
 346        if let entry = entry(path) { return entry.buffer.document.text }
 347        guard let bytes = try? fileSystem.read(URL(fileURLWithPath: path)) else { return nil }
 348        let state = loaded(bytes, path: path)
 349        return state.isEditable ? state.text : nil
 350    }
 351
 352    /// A copy of `path`'s text and tree, its buffer's when it's open, for changes made apart
 353    /// and written back with `ReplaceChangedText`.
 354    public func copy(of path: String) -> DocumentState? {
 355        if let entry = entry(path) { return entry.buffer.document }
 356        guard let bytes = try? fileSystem.read(URL(fileURLWithPath: path)) else { return nil }
 357        let state = loaded(bytes, path: path)
 358        return state.isEditable ? state : nil
 359    }
 360
 361    /// The buffer's name as uniquify writes it (`post-forward-angle-brackets`): the file name,
 362    /// with as many of its folders as tell it apart from other open files of the same name.
 363    public func bufferName(_ path: String) -> String {
 364        let name = (path as NSString).lastPathComponent
 365        let others = openPaths.filter { $0 != path && ($0 as NSString).lastPathComponent == name }
 366        guard !others.isEmpty else { return name }
 367        func folders(_ p: String) -> [String] { (p as NSString).deletingLastPathComponent.split(separator: "/").map(String.init).reversed() }
 368        let mine = folders(path)
 369        var count = 1
 370        while count < mine.count, others.contains(where: { folders($0).prefix(count) == mine.prefix(count) }) { count += 1 }
 371        return name + "<" + mine.prefix(count).reversed().joined(separator: "/") + ">"
 372    }
 373
 374    public func isOpen(_ path: String) -> Bool { entry(path) != nil }
 375
 376    /// The document of an open file, whichever pane shows it.
 377    public func document(of path: String) -> DocumentState? { entry(path)?.buffer.document }
 378
 379    /// Whether `buffer` is the live state of `path`, as `attach` made it.
 380    public func isAttached(_ buffer: DocumentBuffer, for path: String) -> Bool { entry(path)?.buffer === buffer }
 381
 382    /// The caret of an open file.
 383    public func caret(of path: String) -> Int? { entry(path)?.buffer.selection.first?.lowerBound }
 384
 385    /// The text of every open file, for views that read files (the agenda, search).
 386    public var openDocuments: [(path: String, document: DocumentState)] {
 387        entries.map { ($0.path, $0.buffer.document) }
 388    }
 389
 390    /// The text of every open file by path, for the agenda and what it writes (widgets, the
 391    /// watch, reminders). Encrypted files, and files with entries decrypted that saving
 392    /// encrypts, are left out: those views read them from disk.
 393    public var openTexts: [String: String] {
 394        let shown = entries.filter { !crypt.isPrivate($0.buffer.document.text, for: $0.path) }
 395        return Dictionary(shown.map { ($0.path, $0.buffer.document.text) }, uniquingKeysWith: { a, _ in a })
 396    }
 397
 398    /// The text of `path` for an export that writes files (iCalendar, publishing): an open
 399    /// buffer's, unless it holds what's encrypted on disk, then what's on disk; nil for an
 400    /// encrypted file.
 401    public func exportText(of path: String) -> String? {
 402        if Self.isEncryptedFile(path) { return nil }
 403        if let entry = entry(path), !crypt.isPrivate(entry.buffer.document.text, for: entry.path) { return entry.buffer.document.text }
 404        return (try? diskFileSystem.read(URL(fileURLWithPath: path))).flatMap { $0 }.flatMap { String(bytes: $0, encoding: .utf8) }
 405    }
 406
 407    /// Whether `exportText` leaves `path` out or reads it from disk for what's encrypted.
 408    public func exportLeavesOut(_ path: String) -> Bool {
 409        Self.isEncryptedFile(path) || entry(path).map { crypt.isPrivate($0.buffer.document.text, for: $0.path) } == true
 410    }
 411
 412    /// Why the buffer of `path` isn't copied to a temporary file for Emacs (recalculating,
 413    /// exporting, `elisp:` links): it's an encrypted file, or holds entries encrypted on disk.
 414    public func refusesEmacsCopy(_ path: String) -> String? {
 415        let name = (path as NSString).lastPathComponent
 416        if Self.isEncryptedFile(path) { return String(localized: "\(name) is encrypted, so Emacs isn't given a copy of it.") }
 417        guard let entry = entry(path), crypt.isPrivate(entry.buffer.document.text, for: entry.path) else { return nil }
 418        return String(localized: "\(name) has decrypted entries that are encrypted on disk, so Emacs isn't given a copy of it.")
 419    }
 420
 421    /// Said after an export that left out encrypted files or read decrypted entries from disk.
 422    public static var exportNote: String {
 423        String(localized: "Encrypted files were left out, and encrypted entries were exported as they are on disk.")
 424    }
 425
 426    /// Open buffers, most recently shown first.
 427    public var recentPaths: [String] { history.filter(isOpen) }
 428
 429    /// Shows the buffer of `path` in the focused pane, opening the file if it isn't open.
 430    public func open(_ path: String) {
 431        open(path, in: focused)
 432    }
 433
 434    /// Shows the buffer of `path` in `pane`, opening the file if it isn't open.
 435    public func open(_ path: String, in pane: EditorPane) {
 436        let interval = Perf.begin("session.open")
 437        defer { interval.end((path as NSString).lastPathComponent) }
 438        if let existing = entry(path) {
 439            show(existing, in: pane)
 440            return
 441        }
 442        if Self.isEncryptedFile(path), crypt.passphrase(for: path) == nil,
 443           (try? diskFileSystem.read(URL(fileURLWithPath: path)))??.isEmpty == false {
 444            unlockRequest = path
 445            unlockPane = pane
 446            return
 447        }
 448        do {
 449            guard let bytes = try fileSystem.read(URL(fileURLWithPath: path)) else {
 450                showError(String(localized: "Couldn't Open File", comment: "Error alert title"), "\((path as NSString).lastPathComponent) no longer exists.")
 451                return
 452            }
 453            let entry = Entry(path: path, buffer: StateBuffer(loaded(bytes, path: path)))
 454            let index = pane.path.flatMap(self.entry).flatMap { c in entries.firstIndex { $0 === c } }.map { $0 + 1 } ?? entries.count
 455            entries.insert(entry, at: index)
 456            show(entry, in: pane)
 457        } catch {
 458            showError(String(localized: "Couldn't Open File", comment: "Error alert title"), "Can't open \(path): \(error.localizedDescription)")
 459        }
 460    }
 461
 462    private func show(_ entry: Entry, in pane: EditorPane) {
 463        pane.path = entry.path
 464        if !pane.shown.contains(entry.path) { pane.shown.append(entry.path) }
 465        pane.history.removeAll { $0 == entry.path }
 466        pane.history.insert(entry.path, at: 0)
 467        pane.revealRequest = nil
 468        history.removeAll { $0 == entry.path }
 469        history.insert(entry.path, at: 0)
 470        refresh(pane)
 471    }
 472
 473    /// The buffer before or after the focused one, wrapping, in the focused pane.
 474    public func cycle(_ step: Int) {
 475        guard let current, let index = entries.firstIndex(where: { $0 === current }), entries.count > 1 else { return }
 476        show(entries[((index + step) % entries.count + entries.count) % entries.count], in: focused)
 477    }
 478
 479    /// The buffer shown before the focused one.
 480    public func showPrevious() {
 481        guard let previous = recentPaths.dropFirst().first else { return }
 482        open(previous)
 483    }
 484
 485    /// Closes the buffer of `path` without saving it. A pane showing it shows the buffer it
 486    /// showed before, else the most recent other buffer, else nothing.
 487    public func kill(_ path: String) {
 488        guard let entry = entry(path) else { return }
 489        entry.autosave?.cancel()
 490        entries.removeAll { $0 === entry }
 491        crypt.close(entry.path)
 492        held[entry.path] = nil
 493        refusedKeychain.remove(entry.path)
 494        history.removeAll { $0 == path }
 495        outlineUpdates[path]?.cancel()
 496        outlineUpdates[path] = nil
 497        for pane in panes {
 498            pane.shown.removeAll { $0 == path }
 499            pane.history.removeAll { $0 == path }
 500            guard pane.path == path else { continue }
 501            if let next = pane.history.first.flatMap(self.entry) ?? recentPaths.first.flatMap(self.entry) ?? entries.last {
 502                show(next, in: pane)
 503            } else {
 504                pane.path = nil
 505                pane.outline = []
 506                pane.isDirty = false
 507                pane.isReadOnly = false
 508                pane.conflict = nil
 509                pane.revealRequest = nil
 510            }
 511        }
 512        refreshLists()
 513    }
 514
 515    /// Closes the focused buffer without saving, as when its file was deleted.
 516    public func close() {
 517        if let path { kill(path) }
 518    }
 519
 520    /// Makes `buffer`, built from `document`, the live state of the focused file.
 521    public func attach(_ buffer: DocumentBuffer) {
 522        if let path { attach(buffer, for: path) }
 523    }
 524
 525    /// Makes `buffer`, built from the file's `document`, the live state of `path`.
 526    public func attach(_ buffer: DocumentBuffer, for path: String) {
 527        guard let entry = entry(path) else { return }
 528        entry.buffer = buffer
 529        for pane in panes(showing: path) { refresh(pane) }
 530    }
 531
 532    /// The buffer of `path` changed in its editor: the panes showing it update their views
 533    /// once typing pauses, and it saves on its own.
 534    public func bufferChanged(_ path: String) {
 535        guard let entry = entry(path) else { return }
 536        changed(entry)
 537    }
 538
 539    /// The focused buffer changed through typing.
 540    public func bufferChanged() {
 541        if let current { changed(current) }
 542    }
 543
 544    /// A buffer changed, typed or not: the panes showing it update their views, the outline
 545    /// once typing pauses, and it saves on its own.
 546    private func changed(_ entry: Entry) {
 547        let showing = panes(showing: entry.path)
 548        for pane in showing { refresh(pane, outline: false) }
 549        outlineUpdates[entry.path]?.cancel()
 550        if !showing.isEmpty {
 551            let path = entry.path
 552            outlineUpdates[path] = Task { [weak self, weak entry] in
 553                try? await Task.sleep(for: .milliseconds(300))
 554                guard !Task.isCancelled, let self, let entry else { return }
 555                let outline = Self.isOrgPath(path) ? Presentation.outline(entry.buffer.document.tree) : []
 556                for pane in self.panes(showing: path) {
 557                    pane.outline = outline
 558                    pane.editVersion += 1
 559                }
 560            }
 561        }
 562        scheduleAutosave(entry)
 563        refreshLists()
 564        textChanged?(entry.path)
 565    }
 566
 567    /// `pane`'s view of its buffer, from the buffer's state.
 568    private func refresh(_ pane: EditorPane, outline updateOutline: Bool = true) {
 569        let interval = Perf.begin("session.refresh")
 570        defer { interval.end() }
 571        refreshLists()
 572        guard let entry = pane.path.flatMap(entry) else { return }
 573        let state = entry.buffer.document
 574        if pane.isDirty != state.isDirty { pane.isDirty = state.isDirty }
 575        if pane.isReadOnly == state.isEditable { pane.isReadOnly = !state.isEditable }
 576        if pane.conflict != entry.conflict { pane.conflict = entry.conflict }
 577        if updateOutline {
 578            pane.outline = Self.isOrgPath(entry.path) ? Presentation.outline(state.tree) : []
 579            pane.editVersion += 1
 580        }
 581    }
 582
 583    /// Every pane showing `entry`, from the buffer's state.
 584    private func refresh(_ entry: Entry) {
 585        for pane in panes(showing: entry.path) { refresh(pane) }
 586    }
 587
 588    /// The focused pane, from its buffer's state.
 589    private func refresh() {
 590        refresh(focused)
 591    }
 592
 593    private func refreshLists() {
 594        let paths = entries.map(\.path)
 595        if paths != openPaths { openPaths = paths }
 596        let dirty = Set(entries.filter { $0.buffer.document.isDirty }.map(\.path))
 597        if dirty != dirtyPaths { dirtyPaths = dirty }
 598    }
 599
 600    // MARK: - Saving
 601
 602    private var saver: Saver {
 603        Saver(fileSystem: WriteReporting(base: fileSystem) { [weak self] url in MainActor.assumeIsolated { self?.fileWritten?(url.path) } }, recovery: recovery)
 604    }
 605
 606    private func scheduleAutosave(_ entry: Entry) {
 607        entry.autosave?.cancel()
 608        // A held file whose edits were undone, or whose tagged entries went, isn't held.
 609        if held[entry.path] != nil, updateHold(entry) == nil { refresh(entry) }
 610        guard saveMode == .automatic, entry.buffer.document.isDirty, entry.conflict == nil else { return }
 611        entry.autosave = Task { [weak self, weak entry, autosaveDelay] in
 612            try? await Task.sleep(for: autosaveDelay)
 613            guard !Task.isCancelled, let self, let entry else { return }
 614            self.save(entry)
 615        }
 616    }
 617
 618    /// Saves the current buffer now. True when nothing is left unsaved.
 619    @discardableResult
 620    public func save() -> Bool {
 621        guard let current else { return true }
 622        return save(current)
 623    }
 624
 625    /// Saves the buffer of `path`. True when nothing is left unsaved.
 626    @discardableResult
 627    public func save(_ path: String) -> Bool {
 628        guard let entry = entry(path) else { return true }
 629        return save(entry)
 630    }
 631
 632    /// Saves every open buffer. True when nothing is left unsaved.
 633    @discardableResult
 634    public func saveAll() -> Bool {
 635        entries.map { save($0) }.allSatisfy { $0 }
 636    }
 637
 638    @discardableResult
 639    private func save(_ entry: Entry) -> Bool {
 640        let interval = Perf.begin("session.save")
 641        defer { interval.end((entry.path as NSString).lastPathComponent) }
 642        entry.autosave?.cancel()
 643        let name = (entry.path as NSString).lastPathComponent
 644        guard updateHold(entry) == nil else {
 645            askKeychain(entry)
 646            refresh(entry)
 647            return false
 648        }
 649        guard entry.buffer.document.isDirty else { return true }
 650        guard entry.conflict == nil else { return false }
 651        do {
 652            let outcome = try entry.buffer.update { try saver.save(&$0, to: URL(fileURLWithPath: entry.path)) }
 653            switch outcome {
 654            case .saved, .mergedAndSaved:
 655                break
 656            case .conflict:
 657                entry.conflict = "\(name) changed on disk, and the changes conflict with yours."
 658            case .overwroteExternalChange(let change), .changedAfterWrite(let change):
 659                if case .conflict = change {
 660                    entry.conflict = "\(name) changed on disk while saving, and the changes conflict with yours."
 661                }
 662            }
 663        } catch {
 664            showError(String(localized: "Couldn't Save File", comment: "Error alert title"), "Can't save \(name): \(error.localizedDescription)")
 665        }
 666        refresh(entry)
 667        return !entry.buffer.document.isDirty
 668    }
 669
 670    /// Resolves a conflict by writing the buffer over the disk version, which goes to recovery.
 671    public func keepMine() {
 672        guard let buffer, let url else { return }
 673        if let current, updateHold(current) != nil { return refresh() }
 674        do {
 675            try buffer.update { try saver.overwrite(&$0, to: url) }
 676            current?.conflict = nil
 677        } catch {
 678            showError(String(localized: "Couldn't Save File", comment: "Error alert title"), "Can't save \(name): \(error.localizedDescription)")
 679        }
 680        refresh()
 681    }
 682
 683    /// Resolves a conflict by loading the disk version; the buffer goes to recovery.
 684    public func useDiskVersion() {
 685        guard let buffer, let url else { return }
 686        do {
 687            guard let bytes = try fileSystem.read(url) else { return }
 688            if isDirty { try recovery.keep(try buffer.document.encodedText(), for: url, label: "local") }
 689            let path = url.path
 690            buffer.update { $0 = loaded(bytes, path: path) }
 691            current?.conflict = nil
 692        } catch let hold as CryptHold {
 693            showError(String(localized: "Couldn't Keep a Copy", comment: "Error alert title"), keepFailure(hold))
 694        } catch {
 695            showError(String(localized: "Couldn't Read File", comment: "Error alert title"), "Can't read \(name): \(error.localizedDescription)")
 696        }
 697        refresh()
 698    }
 699
 700    // MARK: - Comparing versions
 701
 702    /// The buffer, the file on disk and the version both started from, while they conflict.
 703    public func conflictVersions() -> (mine: String, disk: String, base: String)? {
 704        guard current?.conflict != nil, let buffer, let url, let disk = try? fileSystem.read(url) else { return nil }
 705        return (buffer.document.text, SourceText(bytes: disk).text, SourceText(bytes: buffer.document.mergeBase).text)
 706    }
 707
 708    /// Resolves a conflict as `git merge` leaves one: the buffer holds both sides' changes, those
 709    /// that conflict between markers, to fix and save. The disk version becomes the base, and
 710    /// the buffer as it was goes to recovery.
 711    public func mergeConflictWithMarkers() {
 712        guard let versions = conflictVersions(), let buffer, let url, let disk = try? fileSystem.read(url) else { return }
 713        do {
 714            try recovery.keep(try buffer.document.encodedText(), for: url, label: "local")
 715            let merged = mergeWithMarkers(base: versions.base, ours: versions.mine, theirs: versions.disk, oursLabel: "yours", theirsLabel: "disk")
 716            try buffer.update { state in
 717                state = loaded(disk, path: url.path)
 718                try state.apply(lineEdits(from: versions.disk, to: merged), baseRevision: state.revision)
 719            }
 720            current?.conflict = nil
 721        } catch let hold as CryptHold {
 722            showError(String(localized: "Couldn't Keep a Copy", comment: "Error alert title"), keepFailure(hold))
 723        } catch {
 724            showError(String(localized: "Couldn't Merge", comment: "Error alert title"), "Can't merge \(name): \(error.localizedDescription)")
 725        }
 726        refresh()
 727    }
 728
 729    /// Syncthing's conflict copies of the open file beside it: `name.sync-conflict-DATE-TIME-ID.ext`.
 730    public func syncConflictCopies() -> [URL] {
 731        guard let url else { return [] }
 732        let folder = url.deletingLastPathComponent()
 733        let stem = NSRegularExpression.escapedPattern(for: url.deletingPathExtension().lastPathComponent)
 734        let ext = url.pathExtension.isEmpty ? "" : "\\." + NSRegularExpression.escapedPattern(for: url.pathExtension)
 735        let pattern = "^" + stem + "\\.sync-conflict-[0-9]{8}-[0-9]{6}-[A-Z0-9]+" + ext + "$"
 736        let names = (try? FileManager.default.contentsOfDirectory(atPath: folder.path)) ?? []
 737        return names.filter { $0.range(of: pattern, options: .regularExpression) != nil }.sorted().map { folder.appendingPathComponent($0) }
 738    }
 739
 740    /// What to do with a conflict copy: keep the file as it is, take the copy's text, or merge
 741    /// the two with markers. The copy goes to recovery and is removed.
 742    public enum CopyResolution { case keepFile, useCopy, merge }
 743
 744    public func resolve(copy: URL, _ resolution: CopyResolution) -> String? {
 745        guard let buffer, let url else { return "No file is open" }
 746        do {
 747            guard let bytes = try diskFileSystem.read(copy).map({ try crypt.plain($0, for: url.path) }) else { return "\(copy.lastPathComponent) is gone" }
 748            let copyText = SourceText(bytes: bytes).text
 749            let mine = buffer.document.text
 750            let new: String? = switch resolution {
 751            case .keepFile: nil
 752            case .useCopy: copyText
 753            case .merge: mergeWithMarkers(base: nil, ours: mine, theirs: copyText, oursLabel: url.lastPathComponent, theirsLabel: copy.lastPathComponent)
 754            }
 755            if let new, new != mine {
 756                let result = EditResult(baseRevision: buffer.document.revision, edits: lineEdits(from: mine, to: new))
 757                if case .failed(let message) = buffer.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
 758            }
 759            try recovery.keep(bytes, for: url, label: "sync-conflict")
 760            try FileManager.default.removeItem(at: copy)
 761        } catch {
 762            return "Can't resolve \(copy.lastPathComponent): \(error.localizedDescription)"
 763        }
 764        if let current { changed(current) }
 765        return nil
 766    }
 767
 768    /// Versions of the open file kept in recovery, newest first, with when and why each was
 769    /// kept.
 770    public func recoveryVersions() -> [(url: URL, date: Date, label: String)] {
 771        guard let url, let store = diskRecovery as? FileRecoveryStore, let versions = try? store.versions(for: url) else { return [] }
 772        // `STAMP-LABEL-UUID8-NAME`, as `FileRecoveryStore.keep` names them.
 773        return versions.reversed().map { version in
 774            let m = version.lastPathComponent.firstMatch(of: /^([0-9]+)-(.+?)-([0-9A-Fa-f]{8})-/)
 775            let nanos = m.flatMap { UInt64($0.1) } ?? 0
 776            return (version, Date(timeIntervalSince1970: Double(nanos) / 1_000_000_000), m.map { String($0.2) } ?? "")
 777        }
 778    }
 779
 780    /// The text of a kept version.
 781    public func recoveryText(_ version: URL) -> String? {
 782        guard let bytes = (try? diskFileSystem.read(version)).flatMap({ $0 }) else { return nil }
 783        // Kept as the open file is: encrypted with its passphrase, its entries' messages known.
 784        return (try? path.map { try crypt.plain(bytes, for: $0) } ?? bytes).map { SourceText(bytes: $0).text }
 785    }
 786
 787    /// Puts a kept version's text in the buffer, as an edit that can be undone; the buffer as it
 788    /// was goes to recovery.
 789    public func restore(_ version: URL) -> String? {
 790        guard let text = recoveryText(version) else { return "Can't read that version" }
 791        return restore(text: text)
 792    }
 793
 794    /// Puts `text`, an earlier version of the file, in the buffer as an edit that can be undone;
 795    /// the buffer as it was goes to recovery.
 796    public func restore(text: String) -> String? {
 797        guard let buffer, let url else { return "Can't read that version" }
 798        do {
 799            try recovery.keep(try buffer.document.encodedText(), for: url, label: "local")
 800        } catch let hold as CryptHold {
 801            return keepFailure(hold)
 802        } catch {
 803            return "Can't keep the current version: \(error.localizedDescription)"
 804        }
 805        let mine = buffer.document.text
 806        let result = EditResult(baseRevision: buffer.document.revision, edits: lineEdits(from: mine, to: text))
 807        if case .failed(let message) = buffer.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
 808        if let current { changed(current) }
 809        return nil
 810    }
 811
 812    // MARK: - Moving subtrees
 813
 814    /// The current context of the buffer, as commands see it.
 815    private func editContext(now: Date) -> EditContext? {
 816        guard let buffer else { return nil }
 817        let document = buffer.document
 818        return EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: buffer.selection, now: now, options: options)
 819    }
 820
 821    /// The file and context a subtree command works on: `from` (a file and a heading in it,
 822    /// as the agenda gives them), or the current buffer at its caret.
 823    private func source(_ from: (path: String, offset: Int)?, now: Date) -> (path: String, context: EditContext)? {
 824        guard let from else {
 825            guard let path, let context = editContext(now: now) else { return nil }
 826            return (path, context)
 827        }
 828        let state: DocumentState
 829        if let open = entry(from.path) {
 830            state = open.buffer.document
 831        } else {
 832            guard let bytes = try? fileSystem.read(URL(fileURLWithPath: from.path)) else { return nil }
 833            state = loaded(bytes, path: from.path)
 834        }
 835        guard state.isEditable else { return nil }
 836        let context = EditContext(revision: state.revision, text: state.text, tree: state.tree, selection: [from.offset..<from.offset], now: now, options: options)
 837        return (from.path, context)
 838    }
 839
 840    /// Applies an edit computed from `source(_:now:)` to that file, open or not.
 841    private func applySource(_ edit: EditResult, path: String, now: Date) -> String? {
 842        if case .failed(let message) = perform(PrecomputedEdit(edit), path: path, at: 0, expect: nil, now: now) { return message }
 843        return nil
 844    }
 845
 846    /// Moves the subtree at the caret, or at `from`, under `target`, or with `keep` copies it
 847    /// there (`org-copy`). For another file, that file is written first, through the save
 848    /// path; the subtree leaves its file only once it has. Returns a message for the echo area.
 849    @discardableResult
 850    public func refile(to target: RefileTarget, from: (path: String, offset: Int)? = nil, keep: Bool = false, now: Date = Date()) -> String? {
 851        guard var (path, context) = source(from, now: now) else { return from == nil ? nil : "Can't read the entry's file." }
 852        if target.path != path {
 853            switch prepareMove(path, context: context, to: target.path) {
 854            case .refused(let message): return message
 855            case .sealed(let heading):
 856                guard let again = source((path, heading), now: now) else { return "Can't read the entry's file." }
 857                context = again.context
 858            case .ready: break
 859            }
 860        }
 861        let done = (keep ? "Copied to " : "Refiled to ") + target.label
 862        if target.path == path {
 863            let answers = ["refile": target.start.map(String.init) ?? ""]
 864            let command = RefileWithinFile(keep: keep)
 865            let step = from == nil ? buffer?.perform(command, now: now, answers: answers)
 866                : perform(command, path: path, at: from!.offset, expect: nil, answers: answers, now: now)
 867            if case .failed(let message)? = step { return message }
 868            if from == nil { bufferChanged() }
 869            return done
 870        }
 871        let url = URL(fileURLWithPath: target.path)
 872        let targetName = (target.path as NSString).lastPathComponent
 873        // A target open in a buffer takes the subtree there, with its unsaved edits.
 874        if let open = entry(target.path) {
 875            let state = open.buffer.document
 876            guard state.isEditable else { return "\(targetName) isn't UTF-8, so it can't be changed." }
 877            guard let start = target.locate(in: state) else { return "Can't find \(target.label) any more." }
 878            guard let result = Refile.toOtherFile(source: context, target: state.text, under: start, keep: keep) else { return "Can't refile from here." }
 879            let edit = EditResult(baseRevision: state.revision, edits: [result.target])
 880            if case .failed(let message) = open.buffer.perform(PrecomputedEdit(edit), now: now, answers: [:]) { return message }
 881            changed(open)
 882            if !keep, let message = applySource(result.source, path: path, now: now) { return message }
 883            return done
 884        }
 885        do {
 886            guard let bytes = try fileSystem.read(url) else { return "\(targetName) no longer exists." }
 887            var state = loaded(bytes, path: url.path)
 888            guard state.isEditable else { return "\(targetName) isn't UTF-8, so it can't be changed." }
 889            guard let start = target.locate(in: state) else { return "Can't find \(target.label) any more." }
 890            guard let result = Refile.toOtherFile(source: context, target: state.text, under: start, keep: keep) else { return "Can't refile from here." }
 891            try state.apply([result.target], baseRevision: state.revision)
 892            if case .conflict = try saver.save(&state, to: url) { return "\(targetName) changed on disk; nothing was refiled." }
 893            if !keep, let message = applySource(result.source, path: path, now: now) { return message }
 894            return done
 895        } catch {
 896            return "Can't refile: \(error.localizedDescription)"
 897        }
 898    }
 899
 900    /// `org-refile-new-child`: a heading `title` at the end of `parent`'s subtree, one level
 901    /// below it, or at the end of the file for a file target. Returns the new heading as a
 902    /// target, or a message.
 903    public func createRefileChild(under parent: RefileTarget, title: String, now: Date = Date()) -> Result<RefileTarget, RefileFailure> {
 904        let name = (parent.path as NSString).lastPathComponent
 905        func insert(into state: DocumentState) -> (edit: TextEdit, start: Int, level: Int)? {
 906            guard let start = parent.locate(in: state) else { return nil }
 907            return Self.newChild(state.text, under: start, title: title)
 908        }
 909        func target(_ start: Int, _ level: Int, _ hash: String) -> RefileTarget {
 910            RefileTarget(label: parent.label + "/" + title, path: parent.path, start: start, title: title, level: level, contentHash: hash)
 911        }
 912        if let open = entry(parent.path) {
 913            let state = open.buffer.document
 914            guard state.isEditable else { return .failure(.message("\(name) isn't UTF-8, so it can't be changed.")) }
 915            guard let (edit, start, level) = insert(into: state) else { return .failure(.message("Can't find \(parent.label) any more.")) }
 916            if case .failed(let message) = open.buffer.perform(PrecomputedEdit(EditResult(baseRevision: state.revision, edits: [edit])), now: now, answers: [:]) {
 917                return .failure(.message(message))
 918            }
 919            changed(open)
 920            return .success(target(start, level, ""))
 921        }
 922        do {
 923            let url = URL(fileURLWithPath: parent.path)
 924            guard let bytes = try fileSystem.read(url) else { return .failure(.message("\(name) no longer exists.")) }
 925            var state = loaded(bytes, path: url.path)
 926            guard state.isEditable else { return .failure(.message("\(name) isn't UTF-8, so it can't be changed.")) }
 927            guard let (edit, start, level) = insert(into: state) else { return .failure(.message("Can't find \(parent.label) any more.")) }
 928            try state.apply([edit], baseRevision: state.revision)
 929            if case .conflict = try saver.save(&state, to: url) { return .failure(.message("\(name) changed on disk; nothing was added.")) }
 930            return .success(target(start, level, FileRecord.hash(state.mergeBase)))
 931        } catch {
 932            return .failure(.message("Can't add \(title): \(error.localizedDescription)"))
 933        }
 934    }
 935
 936    public enum RefileFailure: Error, Equatable {
 937        case message(String)
 938    }
 939
 940    /// The edit `org-refile-new-child` makes in `text` under the heading at `start` (nil for
 941    /// the file), and where the new heading starts and its level.
 942    static func newChild(_ text: String, under start: Int??, title: String) -> (edit: TextEdit, start: Int, level: Int) {
 943        let ns = text as NSString
 944        var prefix = ""
 945        var pos = ns.length
 946        var level = 1
 947        if case .some(.some(let heading)) = start {
 948            var stars = 0
 949            while heading + stars < ns.length, ns.character(at: heading + stars) == 42 { stars += 1 }
 950            level = stars + 1
 951            // `org-end-of-subtree t t`: the next heading at this level or above.
 952            var at = NSMaxRange(ns.lineRange(for: NSRange(location: heading, length: 0)))
 953            pos = ns.length
 954            while at < ns.length {
 955                let line = ns.lineRange(for: NSRange(location: at, length: 0))
 956                var n = 0
 957                while at + n < NSMaxRange(line), ns.character(at: at + n) == 42 { n += 1 }
 958                if n > 0, n <= stars, at + n < ns.length, [32, 9].contains(ns.character(at: at + n)) {
 959                    pos = at
 960                    break
 961                }
 962                at = NSMaxRange(line)
 963            }
 964        } else if ns.length > 0, ns.character(at: ns.length - 1) != 10 {
 965            prefix = "\n"
 966        }
 967        // `org-back-over-empty-lines`.
 968        var back = pos
 969        while back > 0, [32, 9, 10, 13].contains(ns.character(at: back - 1)) { back -= 1 }
 970        var lineAfter = back
 971        while lineAfter < ns.length, ns.character(at: lineAfter) != 10 { lineAfter += 1 }
 972        if lineAfter < ns.length { lineAfter += 1 }
 973        if !prefix.isEmpty { lineAfter = ns.length }
 974        let at = min(lineAfter, pos)
 975        let insertion = prefix + "\n" + String(repeating: "*", count: level) + " " + title + "\n"
 976        let newStart = at + (prefix as NSString).length + 1
 977        return (TextEdit(range: at..<at, replacement: insertion), newStart, level)
 978    }
 979
 980    private enum MovePreparation {
 981        case ready
 982        /// Tagged entries in the subtree were encrypted in its file; its heading starts here.
 983        case sealed(Int)
 984        case refused(String)
 985    }
 986
 987    /// Before the subtree at the caret of `context`, in `path`, moves to the file `target`: an
 988    /// encrypted file's entries go only to another encrypted file, which takes the same
 989    /// passphrase; tagged entries with text in the subtree are encrypted where they are first,
 990    /// since the tag they inherit doesn't go with them.
 991    private func prepareMove(_ path: String, context: EditContext, to target: String) -> MovePreparation {
 992        let from = (path as NSString).lastPathComponent, to = (target as NSString).lastPathComponent
 993        if Self.isEncryptedFile(path) {
 994            guard Self.isEncryptedFile(target) else {
 995                return .refused(String(localized: "\(from) is encrypted, and \(to) isn't; the entry wasn't moved."))
 996            }
 997            if crypt.passphrase(for: target) == nil, let passphrase = crypt.passphrase(for: path) {
 998                let disk = (try? diskFileSystem.read(URL(fileURLWithPath: target))).flatMap { $0 } ?? []
 999                guard CryptVault.opens(disk, passphrase: passphrase) else {
1000                    return .refused(String(localized: "\(to) has another passphrase; open it first."))
1001                }
1002                crypt.unlock(passphrase, for: target)
1003            }
1004        }
1005        guard crypt.sealsEntries(for: path), let heading = OrgCrypt.heading(context.text, at: context.selection.first?.lowerBound ?? 0) else { return .ready }
1006        let end = OrgCrypt.bodyRange(context.text, at: heading)?.upperBound ?? heading
1007        let subtree = heading..<max(heading + 1, end)
1008        guard !OrgCrypt.unencrypted(context.text, tag: cryptTag, within: subtree).isEmpty else { return .ready }
1009        guard let passphrase = crypt.passphrase(for: path) else {
1010            return .refused(String(localized: "Tagged entries in the subtree aren't encrypted; give the passphrase with Encrypt… first."))
1011        }
1012        let sealed: String
1013        do {
1014            sealed = try OrgCrypt.seal(context.text, passphrase: passphrase, tag: cryptTag, within: subtree).text
1015        } catch {
1016            return .refused("\(error)")
1017        }
1018        let edit = EditResult(baseRevision: context.revision, edits: lineEdits(from: context.text, to: sealed))
1019        if let open = entry(path) {
1020            if case .failed(let message) = open.buffer.perform(PrecomputedEdit(edit), now: Date(), answers: [:]) { return .refused(message) }
1021            changed(open)
1022        } else {
1023            do {
1024                guard let bytes = try fileSystem.read(URL(fileURLWithPath: path)) else { return .refused("\(from) no longer exists.") }
1025                var state = loaded(bytes, path: path)
1026                try state.apply(edit.edits, baseRevision: state.revision)
1027                if case .conflict = try saver.save(&state, to: URL(fileURLWithPath: path)) { return .refused("\(from) changed on disk; nothing was moved.") }
1028            } catch {
1029                return .refused("Can't encrypt the entry: \(error.localizedDescription)")
1030            }
1031        }
1032        return .sealed(heading)
1033    }
1034
1035    /// The file `archive(from:now:)` moves the entry to, or nil when it can't tell.
1036    public func archiveFile(from: (path: String, offset: Int)? = nil, now: Date = Date()) -> String? {
1037        guard let (path, context) = source(from, now: now), case .success(let destination) = Archive.destination(context, sourcePath: path) else { return nil }
1038        return destination.path
1039    }
1040
1041    /// Archives the subtree at the caret, or at `from`, where `org-archive-subtree` would.
1042    /// Returns a message.
1043    @discardableResult
1044    public func archive(from: (path: String, offset: Int)? = nil, now: Date = Date()) -> String? {
1045        guard var (path, context) = source(from, now: now) else { return from == nil ? nil : "Can't read the entry's file." }
1046        let destination: Archive.Destination
1047        switch Archive.destination(context, sourcePath: path) {
1048        case .success(let value): destination = value
1049        case .failure(.message(let message)): return message
1050        }
1051        if !destination.isSameFile {
1052            switch prepareMove(path, context: context, to: destination.path) {
1053            case .refused(let message): return message
1054            case .sealed(let heading):
1055                guard let again = source((path, heading), now: now) else { return "Can't read the entry's file." }
1056                context = again.context
1057            case .ready: break
1058            }
1059        }
1060        // An archive file open in a buffer takes the subtree there.
1061        if !destination.isSameFile, let open = entry(destination.path) {
1062            let state = open.buffer.document
1063            let name = (destination.path as NSString).lastPathComponent
1064            guard state.isEditable else { return "\(name) isn't UTF-8, so it can't be changed." }
1065            let edits: Archive.Edits
1066            switch Archive.run(context, sourcePath: path, destination: destination, archiveText: state.text) {
1067            case .success(let value): edits = value
1068            case .failure(.message(let message)): return message
1069            }
1070            if let archiveEdit = edits.archive {
1071                let edit = EditResult(baseRevision: state.revision, edits: [archiveEdit])
1072                if case .failed(let message) = open.buffer.perform(PrecomputedEdit(edit), now: now, answers: [:]) { return message }
1073                changed(open)
1074            }
1075            if let message = applySource(edits.source, path: path, now: now) { return message }
1076            return "Archived to \(name)"
1077        }
1078        do {
1079            let url = URL(fileURLWithPath: destination.path)
1080            let existing = destination.isSameFile ? nil : try fileSystem.read(url)
1081            var state = loaded(existing ?? [], path: url.path)
1082            if !destination.isSameFile, !state.isEditable { return "\(url.lastPathComponent) isn't UTF-8, so it can't be changed." }
1083            let edits: Archive.Edits
1084            switch Archive.run(context, sourcePath: path, destination: destination, archiveText: existing.map { _ in state.text }) {
1085            case .success(let value): edits = value
1086            case .failure(.message(let message)): return message
1087            }
1088            if let archiveEdit = edits.archive {
1089                try state.apply([archiveEdit], baseRevision: state.revision)
1090                if case .conflict = try saver.save(&state, to: url) { return "\(url.lastPathComponent) changed on disk; nothing was archived." }
1091            }
1092            if let message = applySource(edits.source, path: path, now: now) { return message }
1093            return destination.isSameFile ? "Archived under \(destination.heading ?? "the end of the file")" : "Archived to \(url.lastPathComponent)"
1094        } catch {
1095            return "Can't archive: \(error.localizedDescription)"
1096        }
1097    }
1098
1099    // MARK: - Commands from other views
1100
1101    /// Where the heading line `line` is now in `path`: at `offset` if it still reads so, else
1102    /// the copy of the line nearest `offset`. For acting on agenda entries after other edits
1103    /// moved them.
1104    public func locateHeading(path: String, line: String, near offset: Int) -> Int? {
1105        guard let text = entry(path)?.buffer.document.text ?? (try? fileSystem.read(URL(fileURLWithPath: path))).flatMap({ $0.map { SourceText(bytes: $0).text } }) else { return nil }
1106        let ns = text as NSString
1107        let length = (line as NSString).length
1108        if offset + length <= ns.length, ns.substring(with: NSRange(location: offset, length: length)) == line,
1109           offset == 0 || ns.character(at: offset - 1) == 10 {
1110            return offset
1111        }
1112        var best: Int?
1113        var search = NSRange(location: 0, length: ns.length)
1114        while true {
1115            let found = ns.range(of: line, options: [], range: search)
1116            guard found.location != NSNotFound else { break }
1117            let atLineStart = found.location == 0 || ns.character(at: found.location - 1) == 10
1118            let lineEnd = NSMaxRange(found) == ns.length || ns.character(at: NSMaxRange(found)) == 10
1119            if atLineStart, lineEnd, best.map({ abs($0 - offset) > abs(found.location - offset) }) ?? true { best = found.location }
1120            search = NSRange(location: NSMaxRange(found), length: ns.length - NSMaxRange(found))
1121        }
1122        return best
1123    }
1124
1125    /// Runs `command` with the caret at `offset` in the file at `path`, as the agenda does:
1126    /// through the buffer when the file is open, leaving its caret alone; otherwise on the
1127    /// file, written back at once through the save path. `expect` is the heading line the
1128    /// caller saw at a position; if the text there changed, nothing runs.
1129    public func perform(
1130        _ command: any OrgCommand, path: String, at offset: Int, expect: (start: Int, line: String)?,
1131        answers: [String: String] = [:], now: Date = Date()
1132    ) -> CommandStep {
1133        let stale = CommandStep.failed("The entry changed; the agenda has been refreshed.")
1134        func matches(_ text: String) -> Bool {
1135            guard let expect else { return true }
1136            let ns = text as NSString
1137            guard expect.start + (expect.line as NSString).length <= ns.length else { return false }
1138            return ns.substring(with: NSRange(location: expect.start, length: (expect.line as NSString).length)) == expect.line
1139        }
1140        if let entry = entry(path) {
1141            let buffer = entry.buffer
1142            guard matches(buffer.document.text) else { return stale }
1143            do {
1144                let options = self.options
1145                let step = try buffer.update { try $0.run(command, selection: [offset..<offset], now: now, answers: answers, options: options) }
1146                if case .commit = step { changed(entry) }
1147                return step
1148            } catch {
1149                return .failed("\(error)")
1150            }
1151        }
1152        let url = URL(fileURLWithPath: path)
1153        let name = url.lastPathComponent
1154        do {
1155            guard let bytes = try fileSystem.read(url) else { return .failed("\(name) no longer exists.") }
1156            var state = loaded(bytes, path: path)
1157            guard state.isEditable else { return .failed("\(name) isn't UTF-8, so it can't be changed.") }
1158            guard matches(state.text) else { return stale }
1159            let step = try state.run(command, selection: [offset..<offset], now: now, answers: answers, options: options)
1160            if case .commit = step, state.isDirty, case .conflict = try saver.save(&state, to: url) {
1161                return .failed("\(name) changed on disk; nothing was changed.")
1162            }
1163            if case .commit = step { textChanged?(path) }
1164            return step
1165        } catch {
1166            return .failed("Can't change \(name): \(error.localizedDescription)")
1167        }
1168    }
1169
1170    /// Applies `edits`, computed against `expected`, to `path` as one change, as Replace in
1171    /// Files and the renames do. An open buffer takes them as an edit its editor can undo; a
1172    /// buffer with no editor yet, and a file that isn't open, first has its text kept in
1173    /// recovery (labelled `replace`), and the file is written through the save path. Nil when
1174    /// done, else why not; nothing changes when the text is no longer `expected`.
1175    public func applyChanges(_ edits: [TextEdit], to path: String, expecting expected: String, now: Date = Date()) -> String? {
1176        let url = URL(fileURLWithPath: path)
1177        let name = url.lastPathComponent
1178        let stale = "\(name) changed after the search; nothing was changed in it."
1179        if let entry = entry(path) {
1180            let state = entry.buffer.document
1181            guard state.isEditable else { return "\(name) isn't UTF-8, so it can't be changed." }
1182            guard state.text == expected else { return stale }
1183            if entry.buffer is StateBuffer {
1184                // A buffer held for its passphrase keeps no copy: it can't be kept encrypted,
1185                // and the replacement can be undone in the buffer.
1186                do { try recovery.keep(try state.encodedText(), for: url, label: "replace") } catch is CryptHold {} catch {
1187                    return "Can't keep a copy of \(name): \(error.localizedDescription)"
1188                }
1189            }
1190            if case .failed(let message) = entry.buffer.perform(PrecomputedEdit(EditResult(baseRevision: state.revision, edits: edits)), now: now, answers: [:]) {
1191                return message
1192            }
1193            changed(entry)
1194            return nil
1195        }
1196        do {
1197            guard let bytes = try fileSystem.read(url) else { return "\(name) no longer exists." }
1198            var state = loaded(bytes, path: path)
1199            guard state.isEditable else { return "\(name) isn't UTF-8, so it can't be changed." }
1200            guard state.text == expected else { return stale }
1201            try recovery.keep(bytes, for: url, label: "replace")
1202            try state.apply(edits, baseRevision: state.revision)
1203            if case .conflict = try saver.save(&state, to: url) { return "\(name) changed on disk; nothing was changed." }
1204            textChanged?(path)
1205            return nil
1206        } catch {
1207            return "Can't change \(name): \(error.localizedDescription)"
1208        }
1209    }
1210
1211    // MARK: - External work
1212
1213    /// Recalculates a table in Emacs from a snapshot of the buffer, then replaces the table
1214    /// with Emacs's text if it hasn't changed meanwhile. Returns a message for the echo area.
1215    public func recalculateInEmacs(table: Range<Int>, point: Int, form: String) async -> String {
1216        guard let programs = Self.runner else {
1217            #if os(macOS)
1218            return "Tables that need Emacs aren't recalculated in this version of orgstar."
1219            #else
1220            return "Tables that need Emacs aren't recalculated on iOS."
1221            #endif
1222        }
1223        guard let entry = current else { return "No file is open." }
1224        let path = entry.path
1225        if let refusal = refusesEmacsCopy(path) { return refusal }
1226        let snapshot = entry.buffer.document.text as NSString
1227        guard table.upperBound <= snapshot.length else { return "The table moved; try again." }
1228        let old = snapshot.substring(with: NSRange(table))
1229        let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
1230        do {
1231            let new = try await programs.recalculateTable(text: snapshot as String, directory: directory, table: table, point: point, form: form)
1232            guard entries.contains(where: { $0 === entry }) else { return "The file was closed before Emacs finished." }
1233            let current = entry.buffer
1234            let text = current.document.text as NSString
1235            guard table.upperBound <= text.length, text.substring(with: NSRange(table)) == old else {
1236                return "The table changed while Emacs recalculated it; nothing was changed."
1237            }
1238            guard new != old else { return "Recalculated in Emacs" }
1239            let result = EditResult(baseRevision: current.document.revision, edits: [TextEdit(range: table, replacement: new)])
1240            if case .failed(let message) = current.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
1241            changed(entry)
1242            return "Recalculated in Emacs"
1243        } catch is CancellationError {
1244            return "Recalculation canceled"
1245        } catch {
1246            return "\(error)"
1247        }
1248    }
1249
1250    /// Runs a src block and writes its result under it, unless the block changed while it
1251    /// ran. Returns a message for the echo area.
1252    public func runBabel(_ job: BabelJob) async -> String {
1253        guard let entry = current else { return "No file is open." }
1254        let directory = URL(fileURLWithPath: entry.path).deletingLastPathComponent()
1255        let programs = Self.runner
1256        /// A program through `programs`; without it, Emacs Lisp in `Elisp` and js in
1257        /// JavaScriptCore, and nothing else.
1258        func run(_ job: BabelJob) async throws -> BabelOutput {
1259            if let output = job.known { return output }
1260            if let programs { return try await programs.runBabel(job, fileDirectory: directory) }
1261            #if canImport(JavaScriptCore)
1262            if let output = try await JavaScriptBlocks.run(job, directory: directory) { return output }
1263            #endif
1264            if job.calc != nil { return try TableReason.calcBlock(job) }
1265            #if canImport(SQLite3)
1266            if let output = try SQLiteBlocks.run(job, directory: directory) { return output }
1267            #endif
1268            #if canImport(WebKit)
1269            if let output = try await DiagramBlocks.run(job, directory: directory) { return output }
1270            #endif
1271            guard let output = try Babel.evaluateNatively(job) else {
1272                #if os(macOS)
1273                throw Babel.Failure.message(job.lispForm == nil
1274                    ? "\(job.language) blocks don't run in this version of orgstar."
1275                    : "This block uses Emacs Lisp that runs only in Emacs.")
1276                #else
1277                throw Babel.Failure.message(job.lispForm == nil
1278                    ? "\(job.language) blocks need the Mac to run."
1279                    : "This block uses Emacs Lisp that runs only in Emacs, on the Mac.")
1280                #endif
1281            }
1282            return output
1283        }
1284        /// Writes the result to `:file`, when the block asks for that; a message when it can't.
1285        func write(_ job: BabelJob, _ output: BabelOutput) -> String? {
1286            guard let file = Babel.fileResult(job, output: output) else { return nil }
1287            do {
1288                try file.contents.write(to: Self.resultFile(file.path, job: job, directory: directory), atomically: true, encoding: .utf8)
1289                return nil
1290            } catch {
1291                return "Can't write \(file.path): \(error.localizedDescription)"
1292            }
1293        }
1294        // Without programs, a block that refers to one that can't run here runs nothing.
1295        if programs == nil, !job.needs.isEmpty, let language = ([job.language] + job.referenced).first(where: { !Self.inProcess.contains($0) }) {
1296            #if os(macOS)
1297            return "This block needs a \(language) block, and \(language) blocks don't run in this version of orgstar; nothing was run."
1298            #else
1299            return "This block needs a \(language) block, and \(language) blocks need the Mac to run; nothing was run."
1300            #endif
1301        }
1302        do {
1303            // Blocks the `:var`s, `:post` and noweb references refer to run first, one at a time.
1304            // Each is one of the blocks agreed to, or the run stops: the text may have changed
1305            // while a block ran.
1306            var job = job
1307            let approved = job.approved
1308            func agreed(_ block: BabelJob) -> Bool { approved.isEmpty || approved.contains(block.blockText) }
1309            if job.needsFile {
1310                let document = entry.buffer.document
1311                switch Babel.replan(job, file: entry.path, text: document.text, tree: document.tree) {
1312                case .failure(.message(let message)): return message
1313                case .success(let next): job = next
1314                }
1315            }
1316            while let need = job.needs.first {
1317                guard agreed(need.job) else { return "The blocks changed while running; nothing more was run." }
1318                let output = try await run(need.job)
1319                guard entries.contains(where: { $0 === entry }) else { return "The file was closed before the block finished." }
1320                if let message = write(need.job, output) { return message }
1321                let document = entry.buffer.document
1322                switch Babel.resume(job, need: need, output: output, text: document.text, tree: document.tree) {
1323                case .failure(.message(let message)): return message
1324                case .success(let next): job = next
1325                }
1326            }
1327            guard agreed(job) else { return "The blocks changed while running; nothing more was run." }
1328            let output = try await run(job)
1329            guard entries.contains(where: { $0 === entry }) else { return "The file was closed before the block finished." }
1330            if let message = write(job, output) { return message }
1331            let current = entry.buffer
1332            let document = current.document
1333            let done = output.problem ?? "Code block evaluation complete."
1334            switch Babel.finish(job, output: output, text: document.text, settings: document.tree.settings) {
1335            case .failure(.message(let message)):
1336                return message
1337            case .success(let edits):
1338                guard !edits.isEmpty else { return job.finish.params.contains("silent") ? output.problem ?? output.stdout : done }
1339                let result = EditResult(baseRevision: document.revision, edits: edits)
1340                if case .failed(let message) = current.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
1341                changed(entry)
1342                return done
1343            }
1344        } catch is CancellationError {
1345            return "Code block canceled."
1346        } catch Babel.Failure.message(let message) {
1347            return message
1348        } catch {
1349            return "\(error)"
1350        }
1351    }
1352
1353    /// The languages that run without programs.
1354    static let inProcess: Set<String> = ["emacs-lisp", "elisp", "js", "javascript", "calc", "sqlite", "dot", "mermaid"]
1355
1356    /// Where a block's `:file` result goes: relative to `:dir`, itself relative to `directory`.
1357    static func resultFile(_ name: String, job: BabelJob, directory: URL) -> URL {
1358        let runDirectory = job.directory.map { URL(fileURLWithPath: $0, relativeTo: directory).standardizedFileURL } ?? directory
1359        return name.hasPrefix("/") ? URL(fileURLWithPath: name) : runDirectory.appendingPathComponent(name)
1360    }
1361
1362    /// The `:file` the block writes its result to, for the open file; nil without one.
1363    public func resultFile(of job: BabelJob) -> String? {
1364        guard let path, let name = job.finish.file else { return nil }
1365        return Self.resultFile(name, job: job, directory: URL(fileURLWithPath: path).deletingLastPathComponent()).path
1366    }
1367
1368    /// The block running now, to cancel.
1369    @ObservationIgnored private var babelTask: Task<String, Never>?
1370    public private(set) var isRunningBabel = false
1371
1372    /// Runs a src block in the background; its message comes back through `report`.
1373    public func startBabel(_ job: BabelJob, report: @escaping @MainActor (String) -> Void) {
1374        babelTask?.cancel()
1375        isRunningBabel = true
1376        let task = Task { await runBabel(job) }
1377        babelTask = task
1378        Task {
1379            let message = await task.value
1380            if babelTask == task {
1381                babelTask = nil
1382                isRunningBabel = false
1383            }
1384            report(message)
1385        }
1386    }
1387
1388    /// Stops the running block; its results aren't inserted.
1389    public func cancelBabel() {
1390        babelTask?.cancel()
1391    }
1392
1393    // MARK: - Locations
1394
1395    /// Opens the file of `location` if needed and asks the editor to show the heading. Offsets
1396    /// are used only if the buffer matches what was indexed; otherwise the heading is found
1397    /// again by position and title.
1398    public func show(_ location: HeadingLocation) {
1399        if path != location.path { open(location.path) }
1400        guard let document else { return }
1401        let hash = FileRecord.hash(document.mergeBase)
1402        let offset: Int
1403        if !isDirty, hash == location.contentHash {
1404            offset = location.start
1405        } else if location.ordinal == HeadingLocation.fileOrdinal {
1406            offset = 0
1407        } else if location.ordinal < outline.count, outline[location.ordinal].title == location.title {
1408            offset = outline[location.ordinal].start
1409        } else if let entry = outline.first(where: { $0.title == location.title }) {
1410            offset = entry.start
1411        } else {
1412            return
1413        }
1414        reveal(offset)
1415    }
1416
1417    /// Asks the focused pane's editor to show `offset`.
1418    public func reveal(_ offset: Int) {
1419        reveal(offset, in: focused)
1420    }
1421
1422    /// Asks `pane`'s editor to show `offset`.
1423    public func reveal(_ offset: Int, in pane: EditorPane) {
1424        requestID += 1
1425        pane.revealRequest = (offset, requestID)
1426    }
1427
1428    /// Called when the workspace sees a file change on disk: an open buffer of it takes the
1429    /// change in.
1430    public func fileChanged(_ path: String) {
1431        let interval = Perf.begin("session.fileChanged")
1432        defer { interval.end((path as NSString).lastPathComponent) }
1433        guard let entry = entry(path) else { return }
1434        let name = (path as NSString).lastPathComponent
1435        let read: [UInt8]?
1436        do {
1437            read = try fileSystem.read(URL(fileURLWithPath: path))
1438        } catch {
1439            showError(String(localized: "Couldn't Read File", comment: "Error alert title"), "Can't read \(name): \(error.localizedDescription)")
1440            return
1441        }
1442        guard let bytes = read else { return }
1443        let buffer = entry.buffer
1444        guard bytes != buffer.document.mergeBase else { return }
1445        switch buffer.update({ $0.diskChanged(to: bytes) }) {
1446        case .conflict:
1447            entry.autosave?.cancel()
1448            entry.conflict = "\(name) changed on disk, and the changes conflict with yours."
1449        case .merged, .reloaded:
1450            entry.conflict = nil
1451            resolveSetup(entry)
1452            // Edits merged with the disk's still need saving.
1453            scheduleAutosave(entry)
1454        case .unchanged:
1455            break
1456        }
1457        refresh(entry)
1458    }
1459}
1460
1461/// `base`, telling `written` about each file it replaced.
1462private struct WriteReporting: FileSystem {
1463    let base: FileSystem
1464    let written: @Sendable (URL) -> Void
1465
1466    func read(_ url: URL) throws -> [UInt8]? { try base.read(url) }
1467
1468    func replace(_ url: URL, with bytes: [UInt8]) throws -> [UInt8]? {
1469        let replaced = try base.replace(url, with: bytes)
1470        written(url)
1471        return replaced
1472    }
1473}
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