Sources/OrgApp/DocumentSession.swift
634 lines · 29200 bytes
1import Foundation
2import Observation
3import OrgCore
4import OrgDocument
5import OrgIndex
6import OrgPresentation
7
8/// A heading, or a whole file, a subtree can be refiled to.
9public struct RefileTarget: Sendable, Hashable {
10 /// `file.org/Parent/Heading`, as the prompt lists it.
11 public let label: String
12 public let path: String
13 /// Start of the heading when the file had `contentHash`; nil refiles to the end of the file.
14 public let start: Int?
15 public let title: String
16 public let level: Int
17 public let contentHash: String
18
19 public init(label: String, path: String, start: Int?, title: String, level: Int, contentHash: String) {
20 self.label = label
21 self.path = path
22 self.start = start
23 self.title = title
24 self.level = level
25 self.contentHash = contentHash
26 }
27
28 /// The heading's start in `state`: its indexed offset if the text is what was indexed,
29 /// else the first heading with the same title and level. Nil for the end of the file.
30 func locate(in state: DocumentState) -> Int?? {
31 guard let start else { return .some(nil) }
32 if !state.isDirty, FileRecord.hash(state.mergeBase) == contentHash { return .some(start) }
33 let entry = Presentation.outline(state.tree).first { $0.title == title && $0.level == level }
34 return entry.map { .some($0.start) }
35 }
36}
37
38public enum SaveMode: String, Sendable, CaseIterable {
39 /// Save shortly after typing stops.
40 case automatic
41 /// Save only on ⌘S.
42 case explicit
43}
44
45/// The files open in a window, as Emacs's buffers: each keeps its text, caret, undo and
46/// unsaved edits while another is shown. The current buffer's outline, saving and requests
47/// for the editor to show a location are what most views use. The view layer attaches an
48/// editor to each buffer and follows `path` and `revealRequest`.
49@MainActor
50@Observable
51public final class DocumentSession {
52 /// The current buffer's file.
53 public private(set) var path: String?
54 /// A copy of the current buffer's state as of its last change. Not observed: it changes
55 /// on every keystroke; views follow `path`, `isDirty` and `outline`.
56 @ObservationIgnored public private(set) var document: DocumentState?
57 public private(set) var outline: [OutlineEntry] = []
58 /// Bumped when the buffer settles after edits, and when a file opens: views that read
59 /// `document` follow this.
60 public private(set) var editVersion = 0
61 public private(set) var isDirty = false
62 /// The file isn't UTF-8, so it can't be edited or saved.
63 public private(set) var isReadOnly = false
64 /// Set while the buffer and the file on disk conflict; says how to resolve it.
65 public private(set) var conflict: String?
66 /// Bumped to ask the editor to reveal an offset.
67 public private(set) var revealRequest: (offset: Int, id: Int)?
68 /// Open files, in the order buffers were opened (each after the one current then).
69 public private(set) var openPaths: [String] = []
70 /// Open files with unsaved edits.
71 public private(set) var dirtyPaths: Set<String> = []
72 public var lastError: String?
73 public var saveMode: SaveMode = .automatic
74 public var autosaveDelay: Duration = .seconds(1)
75 /// Org options for commands the session runs (refile, archive).
76 public var options: EditingOptions = .org
77 /// TODO keywords and priorities for files without their own settings.
78 public var defaults: OrgSettings = .default
79
80 /// One open file.
81 @MainActor
82 final class Entry {
83 let path: String
84 var buffer: DocumentBuffer
85 var conflict: String?
86 var autosave: Task<Void, Never>?
87
88 init(path: String, buffer: DocumentBuffer) {
89 self.path = path
90 self.buffer = buffer
91 }
92 }
93
94 private let fileSystem: FileSystem
95 private let recovery: RecoveryStore
96 @ObservationIgnored private var entries: [Entry] = []
97 @ObservationIgnored private var current: Entry?
98 /// Paths, most recently shown first.
99 @ObservationIgnored private var history: [String] = []
100 @ObservationIgnored private var outlineUpdate: Task<Void, Never>?
101 private var requestID = 0
102
103 public init(
104 fileSystem: FileSystem = CoordinatedFileSystem(),
105 recovery: RecoveryStore = FileRecoveryStore(directory: WorkspaceModel.defaultDirectory.appendingPathComponent("Recovery"))
106 ) {
107 self.fileSystem = fileSystem
108 self.recovery = recovery
109 }
110
111 private var buffer: DocumentBuffer? { current?.buffer }
112 /// The current buffer's pending autosave, for tests to wait on.
113 var autosave: Task<Void, Never>? { current?.autosave }
114 private var url: URL? { path.map { URL(fileURLWithPath: $0) } }
115 /// Whether the open file is an org file (`.org`, `.org_archive`), not plain text.
116 public var isOrg: Bool { path.map(Self.isOrgPath) ?? false }
117
118 public static func isOrgPath(_ path: String) -> Bool {
119 path.hasSuffix(".org") || path.hasSuffix(".org_archive")
120 }
121
122 /// The caret in the open file.
123 public var caret: Int { buffer?.selection.first?.lowerBound ?? 0 }
124 private var name: String { path.map { ($0 as NSString).lastPathComponent } ?? "" }
125
126 private func entry(_ path: String) -> Entry? { entries.first { $0.path == path } }
127
128 public func isOpen(_ path: String) -> Bool { entry(path) != nil }
129
130 /// The caret of an open file.
131 public func caret(of path: String) -> Int? { entry(path)?.buffer.selection.first?.lowerBound }
132
133 /// The text of every open file, for views that read files (the agenda, search).
134 public var openDocuments: [(path: String, document: DocumentState)] {
135 entries.map { ($0.path, $0.buffer.document) }
136 }
137
138 /// The text of every open file by path, for the agenda.
139 public var openTexts: [String: String] {
140 Dictionary(entries.map { ($0.path, $0.buffer.document.text) }, uniquingKeysWith: { a, _ in a })
141 }
142
143 /// Open buffers, most recently shown first.
144 public var recentPaths: [String] { history.filter(isOpen) }
145
146 /// Shows the buffer of `path`, opening the file if it isn't open.
147 public func open(_ path: String) {
148 if let existing = entry(path) {
149 activate(existing)
150 return
151 }
152 do {
153 guard let bytes = try fileSystem.read(URL(fileURLWithPath: path)) else {
154 lastError = "\((path as NSString).lastPathComponent) no longer exists."
155 return
156 }
157 let entry = Entry(path: path, buffer: StateBuffer(DocumentState(bytes: bytes, defaults: defaults)))
158 let index = current.flatMap { c in entries.firstIndex { $0 === c } }.map { $0 + 1 } ?? entries.count
159 entries.insert(entry, at: index)
160 activate(entry)
161 } catch {
162 lastError = "Can't open \(path): \(error.localizedDescription)"
163 }
164 }
165
166 private func activate(_ entry: Entry) {
167 current = entry
168 path = entry.path
169 conflict = entry.conflict
170 revealRequest = nil
171 history.removeAll { $0 == entry.path }
172 history.insert(entry.path, at: 0)
173 refresh()
174 }
175
176 /// The buffer before or after the current one, wrapping.
177 public func cycle(_ step: Int) {
178 guard let current, let index = entries.firstIndex(where: { $0 === current }), entries.count > 1 else { return }
179 activate(entries[((index + step) % entries.count + entries.count) % entries.count])
180 }
181
182 /// The buffer shown before the current one.
183 public func showPrevious() {
184 guard let previous = recentPaths.dropFirst().first else { return }
185 open(previous)
186 }
187
188 /// Closes the buffer of `path` without saving it; the most recent other buffer shows.
189 public func kill(_ path: String) {
190 guard let entry = entry(path) else { return }
191 entry.autosave?.cancel()
192 entries.removeAll { $0 === entry }
193 history.removeAll { $0 == path }
194 if entry === current {
195 current = nil
196 if let next = recentPaths.first.flatMap(self.entry) ?? entries.last {
197 activate(next)
198 } else {
199 outlineUpdate?.cancel()
200 self.path = nil
201 document = nil
202 outline = []
203 isDirty = false
204 conflict = nil
205 revealRequest = nil
206 refreshLists()
207 }
208 } else {
209 refreshLists()
210 }
211 }
212
213 /// Closes the current buffer without saving, as when its file was deleted.
214 public func close() {
215 if let path { kill(path) }
216 }
217
218 /// Makes `buffer`, built from `document`, the live state of the current file.
219 public func attach(_ buffer: DocumentBuffer) {
220 current?.buffer = buffer
221 refresh()
222 }
223
224 /// The buffer of `path` changed in its editor: the current one updates its views, another
225 /// saves on its own.
226 public func bufferChanged(_ path: String) {
227 guard let entry = entry(path) else { return }
228 if entry === current { bufferChanged() } else { scheduleAutosave(entry); refreshLists() }
229 }
230
231 /// The buffer changed through typing. The outline follows once typing pauses.
232 public func bufferChanged() {
233 refresh(outline: false)
234 outlineUpdate?.cancel()
235 outlineUpdate = Task { [weak self] in
236 try? await Task.sleep(for: .milliseconds(300))
237 guard !Task.isCancelled, let self, let document = self.document else { return }
238 self.outline = self.isOrg ? Presentation.outline(document.tree) : []
239 self.editVersion += 1
240 }
241 if let current { scheduleAutosave(current) }
242 }
243
244 private func refresh(outline updateOutline: Bool = true) {
245 refreshLists()
246 guard let buffer else { return }
247 let state = buffer.document
248 document = state
249 if isDirty != state.isDirty { isDirty = state.isDirty }
250 if isReadOnly == state.isEditable { isReadOnly = !state.isEditable }
251 if conflict != current?.conflict { conflict = current?.conflict }
252 if updateOutline {
253 outline = isOrg ? Presentation.outline(state.tree) : []
254 editVersion += 1
255 }
256 }
257
258 private func refreshLists() {
259 let paths = entries.map(\.path)
260 if paths != openPaths { openPaths = paths }
261 let dirty = Set(entries.filter { $0.buffer.document.isDirty }.map(\.path))
262 if dirty != dirtyPaths { dirtyPaths = dirty }
263 }
264
265 // MARK: - Saving
266
267 private var saver: Saver { Saver(fileSystem: fileSystem, recovery: recovery) }
268
269 private func scheduleAutosave(_ entry: Entry) {
270 entry.autosave?.cancel()
271 guard saveMode == .automatic, entry.buffer.document.isDirty, entry.conflict == nil else { return }
272 entry.autosave = Task { [weak self, weak entry, autosaveDelay] in
273 try? await Task.sleep(for: autosaveDelay)
274 guard !Task.isCancelled, let self, let entry else { return }
275 self.save(entry)
276 }
277 }
278
279 /// Saves the current buffer now. True when nothing is left unsaved.
280 @discardableResult
281 public func save() -> Bool {
282 guard let current else { return true }
283 return save(current)
284 }
285
286 /// Saves the buffer of `path`. True when nothing is left unsaved.
287 @discardableResult
288 public func save(_ path: String) -> Bool {
289 guard let entry = entry(path) else { return true }
290 return save(entry)
291 }
292
293 /// Saves every open buffer. True when nothing is left unsaved.
294 @discardableResult
295 public func saveAll() -> Bool {
296 entries.map { save($0) }.allSatisfy { $0 }
297 }
298
299 @discardableResult
300 private func save(_ entry: Entry) -> Bool {
301 entry.autosave?.cancel()
302 let name = (entry.path as NSString).lastPathComponent
303 guard entry.buffer.document.isDirty else { return true }
304 guard entry.conflict == nil else { return false }
305 do {
306 let outcome = try entry.buffer.update { try saver.save(&$0, to: URL(fileURLWithPath: entry.path)) }
307 switch outcome {
308 case .saved, .mergedAndSaved:
309 break
310 case .conflict:
311 entry.conflict = "\(name) changed on disk, and the changes conflict with yours."
312 case .overwroteExternalChange(let change), .changedAfterWrite(let change):
313 if case .conflict = change {
314 entry.conflict = "\(name) changed on disk while saving, and the changes conflict with yours."
315 }
316 }
317 } catch {
318 lastError = "Can't save \(name): \(error.localizedDescription)"
319 }
320 if entry === current { refresh() } else { refreshLists() }
321 return !entry.buffer.document.isDirty
322 }
323
324 /// Resolves a conflict by writing the buffer over the disk version, which goes to recovery.
325 public func keepMine() {
326 guard let buffer, let url else { return }
327 do {
328 try buffer.update { try saver.overwrite(&$0, to: url) }
329 current?.conflict = nil
330 } catch {
331 lastError = "Can't save \(name): \(error.localizedDescription)"
332 }
333 refresh()
334 }
335
336 /// Resolves a conflict by loading the disk version; the buffer goes to recovery.
337 public func useDiskVersion() {
338 guard let buffer, let url else { return }
339 do {
340 guard let bytes = try fileSystem.read(url) else { return }
341 if isDirty { try recovery.keep(try buffer.document.encodedText(), for: url, label: "local") }
342 buffer.update { $0 = DocumentState(bytes: bytes, defaults: $0.defaults) }
343 current?.conflict = nil
344 } catch {
345 lastError = "Can't read \(name): \(error.localizedDescription)"
346 }
347 refresh()
348 }
349
350 // MARK: - Moving subtrees
351
352 /// The current context of the buffer, as commands see it.
353 private func editContext(now: Date) -> EditContext? {
354 guard let buffer else { return nil }
355 let document = buffer.document
356 return EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: buffer.selection, now: now, options: options)
357 }
358
359 /// Moves the subtree at the caret under `target`. For another file, that file is written
360 /// first, through the save path; the subtree leaves this buffer only once it has. Returns a
361 /// message for the echo area.
362 @discardableResult
363 public func refile(to target: RefileTarget, now: Date = Date()) -> String? {
364 guard let buffer, let path, let context = editContext(now: now) else { return nil }
365 if target.path == path {
366 let step = buffer.perform(RefileWithinFile(), now: now, answers: ["refile": target.start.map(String.init) ?? ""])
367 if case .failed(let message) = step { return message }
368 bufferChanged()
369 return "Refiled to \(target.label)"
370 }
371 let url = URL(fileURLWithPath: target.path)
372 let targetName = (target.path as NSString).lastPathComponent
373 // A target open in a buffer takes the subtree there, with its unsaved edits.
374 if let open = entry(target.path) {
375 let state = open.buffer.document
376 guard state.isEditable else { return "\(targetName) isn't UTF-8, so it can't be changed." }
377 guard let start = target.locate(in: state) else { return "Can't find \(target.label) any more." }
378 guard let result = Refile.toOtherFile(source: context, target: state.text, under: start) else { return "Can't refile from here." }
379 let edit = EditResult(baseRevision: state.revision, edits: [result.target])
380 if case .failed(let message) = open.buffer.perform(PrecomputedEdit(edit), now: now, answers: [:]) { return message }
381 changed(open)
382 if case .failed(let message) = buffer.perform(PrecomputedEdit(result.source), now: now, answers: [:]) { return message }
383 bufferChanged()
384 return "Refiled to \(target.label)"
385 }
386 do {
387 guard let bytes = try fileSystem.read(url) else { return "\(targetName) no longer exists." }
388 var state = DocumentState(bytes: bytes, defaults: defaults)
389 guard state.isEditable else { return "\(targetName) isn't UTF-8, so it can't be changed." }
390 guard let start = target.locate(in: state) else { return "Can't find \(target.label) any more." }
391 guard let result = Refile.toOtherFile(source: context, target: state.text, under: start) else { return "Can't refile from here." }
392 try state.apply([result.target], baseRevision: state.revision)
393 if case .conflict = try saver.save(&state, to: url) { return "\(targetName) changed on disk; nothing was refiled." }
394 if case .failed(let message) = buffer.perform(PrecomputedEdit(result.source), now: now, answers: [:]) { return message }
395 bufferChanged()
396 return "Refiled to \(target.label)"
397 } catch {
398 return "Can't refile: \(error.localizedDescription)"
399 }
400 }
401
402 /// Archives the subtree at the caret where `org-archive-subtree` would. Returns a message.
403 @discardableResult
404 public func archive(now: Date = Date()) -> String? {
405 guard let buffer, let path, let context = editContext(now: now) else { return nil }
406 let destination: Archive.Destination
407 switch Archive.destination(context, sourcePath: path) {
408 case .success(let value): destination = value
409 case .failure(.message(let message)): return message
410 }
411 // An archive file open in a buffer takes the subtree there.
412 if !destination.isSameFile, let open = entry(destination.path) {
413 let state = open.buffer.document
414 let name = (destination.path as NSString).lastPathComponent
415 guard state.isEditable else { return "\(name) isn't UTF-8, so it can't be changed." }
416 let edits: Archive.Edits
417 switch Archive.run(context, sourcePath: path, destination: destination, archiveText: state.text) {
418 case .success(let value): edits = value
419 case .failure(.message(let message)): return message
420 }
421 if let archiveEdit = edits.archive {
422 let edit = EditResult(baseRevision: state.revision, edits: [archiveEdit])
423 if case .failed(let message) = open.buffer.perform(PrecomputedEdit(edit), now: now, answers: [:]) { return message }
424 changed(open)
425 }
426 if case .failed(let message) = buffer.perform(PrecomputedEdit(edits.source), now: now, answers: [:]) { return message }
427 bufferChanged()
428 return "Archived to \(name)"
429 }
430 do {
431 let url = URL(fileURLWithPath: destination.path)
432 let existing = destination.isSameFile ? nil : try fileSystem.read(url)
433 var state = DocumentState(bytes: existing ?? [], defaults: defaults)
434 if !destination.isSameFile, !state.isEditable { return "\(url.lastPathComponent) isn't UTF-8, so it can't be changed." }
435 let edits: Archive.Edits
436 switch Archive.run(context, sourcePath: path, destination: destination, archiveText: existing.map { _ in state.text }) {
437 case .success(let value): edits = value
438 case .failure(.message(let message)): return message
439 }
440 if let archiveEdit = edits.archive {
441 try state.apply([archiveEdit], baseRevision: state.revision)
442 if case .conflict = try saver.save(&state, to: url) { return "\(url.lastPathComponent) changed on disk; nothing was archived." }
443 }
444 if case .failed(let message) = buffer.perform(PrecomputedEdit(edits.source), now: now, answers: [:]) { return message }
445 bufferChanged()
446 return destination.isSameFile ? "Archived under \(destination.heading ?? "the end of the file")" : "Archived to \(url.lastPathComponent)"
447 } catch {
448 return "Can't archive: \(error.localizedDescription)"
449 }
450 }
451
452 // MARK: - Commands from other views
453
454 /// Runs `command` with the caret at `offset` in the file at `path`, as the agenda does:
455 /// through the buffer when the file is open, leaving its caret alone; otherwise on the
456 /// file, written back at once through the save path. `expect` is the heading line the
457 /// caller saw at a position; if the text there changed, nothing runs.
458 public func perform(
459 _ command: any OrgCommand, path: String, at offset: Int, expect: (start: Int, line: String)?,
460 answers: [String: String] = [:], now: Date = Date()
461 ) -> CommandStep {
462 let stale = CommandStep.failed("The entry changed; the agenda has been refreshed.")
463 func matches(_ text: String) -> Bool {
464 guard let expect else { return true }
465 let ns = text as NSString
466 guard expect.start + (expect.line as NSString).length <= ns.length else { return false }
467 return ns.substring(with: NSRange(location: expect.start, length: (expect.line as NSString).length)) == expect.line
468 }
469 if let entry = entry(path) {
470 let buffer = entry.buffer
471 guard matches(buffer.document.text) else { return stale }
472 do {
473 let options = self.options
474 let step = try buffer.update { try $0.run(command, selection: [offset..<offset], now: now, answers: answers, options: options) }
475 if case .commit = step {
476 if entry === current { bufferChanged() } else { scheduleAutosave(entry); refreshLists() }
477 }
478 return step
479 } catch {
480 return .failed("\(error)")
481 }
482 }
483 let url = URL(fileURLWithPath: path)
484 let name = url.lastPathComponent
485 do {
486 guard let bytes = try fileSystem.read(url) else { return .failed("\(name) no longer exists.") }
487 var state = DocumentState(bytes: bytes, defaults: defaults)
488 guard state.isEditable else { return .failed("\(name) isn't UTF-8, so it can't be changed.") }
489 guard matches(state.text) else { return stale }
490 let step = try state.run(command, selection: [offset..<offset], now: now, answers: answers, options: options)
491 if case .commit = step, state.isDirty, case .conflict = try saver.save(&state, to: url) {
492 return .failed("\(name) changed on disk; nothing was changed.")
493 }
494 return step
495 } catch {
496 return .failed("Can't change \(name): \(error.localizedDescription)")
497 }
498 }
499
500 // MARK: - External work
501
502 /// Recalculates a table in Emacs from a snapshot of the buffer, then replaces the table
503 /// with Emacs's text if it hasn't changed meanwhile. Returns a message for the echo area.
504 public func recalculateInEmacs(table: Range<Int>, point: Int, form: String) async -> String {
505 guard let entry = current else { return "No file is open." }
506 let path = entry.path
507 let snapshot = entry.buffer.document.text as NSString
508 guard table.upperBound <= snapshot.length else { return "The table moved; try again." }
509 let old = snapshot.substring(with: NSRange(table))
510 let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
511 do {
512 let new = try await EmacsRunner.recalculateTable(text: snapshot as String, directory: directory, table: table, point: point, form: form)
513 guard entries.contains(where: { $0 === entry }) else { return "The file was closed before Emacs finished." }
514 let current = entry.buffer
515 let text = current.document.text as NSString
516 guard table.upperBound <= text.length, text.substring(with: NSRange(table)) == old else {
517 return "The table changed while Emacs recalculated it; nothing was changed."
518 }
519 guard new != old else { return "Recalculated in Emacs" }
520 let result = EditResult(baseRevision: current.document.revision, edits: [TextEdit(range: table, replacement: new)])
521 if case .failed(let message) = current.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
522 changed(entry)
523 return "Recalculated in Emacs"
524 } catch {
525 return "\(error)"
526 }
527 }
528
529 /// Runs a src block and writes its result under it, unless the block changed while it
530 /// ran. Returns a message for the echo area.
531 public func runBabel(_ job: BabelJob) async -> String {
532 guard let entry = current else { return "No file is open." }
533 let directory = URL(fileURLWithPath: entry.path).deletingLastPathComponent()
534 do {
535 let output = try await BabelRunner.run(job, fileDirectory: directory)
536 guard entries.contains(where: { $0 === entry }) else { return "The file was closed before the block finished." }
537 let current = entry.buffer
538 let document = current.document
539 let done = output.problem ?? "Code block evaluation complete."
540 switch Babel.finish(job, output: output, text: document.text, settings: document.tree.settings) {
541 case .failure(.message(let message)):
542 return message
543 case .success(let edits):
544 guard !edits.isEmpty else { return job.finish.params.contains("silent") ? output.problem ?? output.stdout : done }
545 let result = EditResult(baseRevision: document.revision, edits: edits)
546 if case .failed(let message) = current.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
547 changed(entry)
548 return done
549 }
550 } catch is CancellationError {
551 return "Code block canceled."
552 } catch {
553 return "\(error)"
554 }
555 }
556
557 /// The block running now, to cancel.
558 @ObservationIgnored private var babelTask: Task<String, Never>?
559 public private(set) var isRunningBabel = false
560
561 /// Runs a src block in the background; its message comes back through `report`.
562 public func startBabel(_ job: BabelJob, report: @escaping @MainActor (String) -> Void) {
563 babelTask?.cancel()
564 isRunningBabel = true
565 let task = Task { await runBabel(job) }
566 babelTask = task
567 Task {
568 let message = await task.value
569 if babelTask == task {
570 babelTask = nil
571 isRunningBabel = false
572 }
573 report(message)
574 }
575 }
576
577 /// Stops the running block; its results aren't inserted.
578 public func cancelBabel() {
579 babelTask?.cancel()
580 }
581
582 /// A buffer changed outside typing: the current one updates its views, another saves.
583 private func changed(_ entry: Entry) {
584 if entry === current { bufferChanged() } else { scheduleAutosave(entry); refreshLists() }
585 }
586
587 // MARK: - Locations
588
589 /// Opens the file of `location` if needed and asks the editor to show the heading. Offsets
590 /// are used only if the buffer matches what was indexed; otherwise the heading is found
591 /// again by position and title.
592 public func show(_ location: HeadingLocation) {
593 if path != location.path { open(location.path) }
594 guard let document else { return }
595 let hash = FileRecord.hash(document.mergeBase)
596 let offset: Int
597 if !isDirty, hash == location.contentHash {
598 offset = location.start
599 } else if location.ordinal < outline.count, outline[location.ordinal].title == location.title {
600 offset = outline[location.ordinal].start
601 } else if let entry = outline.first(where: { $0.title == location.title }) {
602 offset = entry.start
603 } else {
604 return
605 }
606 reveal(offset)
607 }
608
609 public func reveal(_ offset: Int) {
610 requestID += 1
611 revealRequest = (offset, requestID)
612 }
613
614 /// Called when the workspace sees a file change on disk: an open buffer of it takes the
615 /// change in.
616 public func fileChanged(_ path: String) {
617 guard let entry = entry(path), let bytes = try? fileSystem.read(URL(fileURLWithPath: path)) else { return }
618 let buffer = entry.buffer
619 guard bytes != buffer.document.mergeBase else { return }
620 let name = (path as NSString).lastPathComponent
621 switch buffer.update({ $0.diskChanged(to: bytes) }) {
622 case .conflict:
623 entry.autosave?.cancel()
624 entry.conflict = "\(name) changed on disk, and the changes conflict with yours."
625 case .merged, .reloaded:
626 entry.conflict = nil
627 // Edits merged with the disk's still need saving.
628 scheduleAutosave(entry)
629 case .unchanged:
630 break
631 }
632 if entry === current { refresh() } else { refreshLists() }
633 }
634}