Sources/OrgApp/DocumentSession.swift

9954efcbf435b2e8d78a4b59bfbbbb67c1b6c379
orgstar/Sources/OrgApp/DocumentSession.swift

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