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