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