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