Sources/OrgApp/DocumentSession.swift

d85099bc95bf1766aee990d94671dacda0c0686e
orgstar/Sources/OrgApp/DocumentSession.swift history · blame · raw

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