Sources/OrgApp/DocumentSession.swift
1202 lines · 60196 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 text = recoveryText(version) else { return "Can't read that version" }
598 return restore(text: text)
599 }
600
601 /// Puts `text`, an earlier version of the file, in the buffer as an edit that can be undone;
602 /// the buffer as it was goes to recovery.
603 public func restore(text: String) -> String? {
604 guard let buffer, let url else { return "Can't read that version" }
605 do {
606 try recovery.keep(try buffer.document.encodedText(), for: url, label: "local")
607 } catch {
608 return "Can't keep the current version: \(error.localizedDescription)"
609 }
610 let mine = buffer.document.text
611 let result = EditResult(baseRevision: buffer.document.revision, edits: lineEdits(from: mine, to: text))
612 if case .failed(let message) = buffer.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
613 if let current { changed(current) }
614 return nil
615 }
616
617 // MARK: - Moving subtrees
618
619 /// The current context of the buffer, as commands see it.
620 private func editContext(now: Date) -> EditContext? {
621 guard let buffer else { return nil }
622 let document = buffer.document
623 return EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: buffer.selection, now: now, options: options)
624 }
625
626 /// The file and context a subtree command works on: `from` (a file and a heading in it,
627 /// as the agenda gives them), or the current buffer at its caret.
628 private func source(_ from: (path: String, offset: Int)?, now: Date) -> (path: String, context: EditContext)? {
629 guard let from else {
630 guard let path, let context = editContext(now: now) else { return nil }
631 return (path, context)
632 }
633 let state: DocumentState
634 if let open = entry(from.path) {
635 state = open.buffer.document
636 } else {
637 guard let bytes = try? fileSystem.read(URL(fileURLWithPath: from.path)) else { return nil }
638 state = loaded(bytes, path: from.path)
639 }
640 guard state.isEditable else { return nil }
641 let context = EditContext(revision: state.revision, text: state.text, tree: state.tree, selection: [from.offset..<from.offset], now: now, options: options)
642 return (from.path, context)
643 }
644
645 /// Applies an edit computed from `source(_:now:)` to that file, open or not.
646 private func applySource(_ edit: EditResult, path: String, now: Date) -> String? {
647 if case .failed(let message) = perform(PrecomputedEdit(edit), path: path, at: 0, expect: nil, now: now) { return message }
648 return nil
649 }
650
651 /// Moves the subtree at the caret, or at `from`, under `target`, or with `keep` copies it
652 /// there (`org-copy`). For another file, that file is written first, through the save
653 /// path; the subtree leaves its file only once it has. Returns a message for the echo area.
654 @discardableResult
655 public func refile(to target: RefileTarget, from: (path: String, offset: Int)? = nil, keep: Bool = false, now: Date = Date()) -> String? {
656 guard let (path, context) = source(from, now: now) else { return from == nil ? nil : "Can't read the entry's file." }
657 let done = (keep ? "Copied to " : "Refiled to ") + target.label
658 if target.path == path {
659 let answers = ["refile": target.start.map(String.init) ?? ""]
660 let command = RefileWithinFile(keep: keep)
661 let step = from == nil ? buffer?.perform(command, now: now, answers: answers)
662 : perform(command, path: path, at: from!.offset, expect: nil, answers: answers, now: now)
663 if case .failed(let message)? = step { return message }
664 if from == nil { bufferChanged() }
665 return done
666 }
667 let url = URL(fileURLWithPath: target.path)
668 let targetName = (target.path as NSString).lastPathComponent
669 // A target open in a buffer takes the subtree there, with its unsaved edits.
670 if let open = entry(target.path) {
671 let state = open.buffer.document
672 guard state.isEditable else { return "\(targetName) isn't UTF-8, so it can't be changed." }
673 guard let start = target.locate(in: state) else { return "Can't find \(target.label) any more." }
674 guard let result = Refile.toOtherFile(source: context, target: state.text, under: start, keep: keep) else { return "Can't refile from here." }
675 let edit = EditResult(baseRevision: state.revision, edits: [result.target])
676 if case .failed(let message) = open.buffer.perform(PrecomputedEdit(edit), now: now, answers: [:]) { return message }
677 changed(open)
678 if !keep, let message = applySource(result.source, path: path, now: now) { return message }
679 return done
680 }
681 do {
682 guard let bytes = try fileSystem.read(url) else { return "\(targetName) no longer exists." }
683 var state = loaded(bytes, path: url.path)
684 guard state.isEditable else { return "\(targetName) isn't UTF-8, so it can't be changed." }
685 guard let start = target.locate(in: state) else { return "Can't find \(target.label) any more." }
686 guard let result = Refile.toOtherFile(source: context, target: state.text, under: start, keep: keep) else { return "Can't refile from here." }
687 try state.apply([result.target], baseRevision: state.revision)
688 if case .conflict = try saver.save(&state, to: url) { return "\(targetName) changed on disk; nothing was refiled." }
689 if !keep, let message = applySource(result.source, path: path, now: now) { return message }
690 return done
691 } catch {
692 return "Can't refile: \(error.localizedDescription)"
693 }
694 }
695
696 /// `org-refile-new-child`: a heading `title` at the end of `parent`'s subtree, one level
697 /// below it, or at the end of the file for a file target. Returns the new heading as a
698 /// target, or a message.
699 public func createRefileChild(under parent: RefileTarget, title: String, now: Date = Date()) -> Result<RefileTarget, RefileFailure> {
700 let name = (parent.path as NSString).lastPathComponent
701 func insert(into state: DocumentState) -> (edit: TextEdit, start: Int, level: Int)? {
702 guard let start = parent.locate(in: state) else { return nil }
703 return Self.newChild(state.text, under: start, title: title)
704 }
705 func target(_ start: Int, _ level: Int, _ hash: String) -> RefileTarget {
706 RefileTarget(label: parent.label + "/" + title, path: parent.path, start: start, title: title, level: level, contentHash: hash)
707 }
708 if let open = entry(parent.path) {
709 let state = open.buffer.document
710 guard state.isEditable else { return .failure(.message("\(name) isn't UTF-8, so it can't be changed.")) }
711 guard let (edit, start, level) = insert(into: state) else { return .failure(.message("Can't find \(parent.label) any more.")) }
712 if case .failed(let message) = open.buffer.perform(PrecomputedEdit(EditResult(baseRevision: state.revision, edits: [edit])), now: now, answers: [:]) {
713 return .failure(.message(message))
714 }
715 changed(open)
716 return .success(target(start, level, ""))
717 }
718 do {
719 let url = URL(fileURLWithPath: parent.path)
720 guard let bytes = try fileSystem.read(url) else { return .failure(.message("\(name) no longer exists.")) }
721 var state = loaded(bytes, path: url.path)
722 guard state.isEditable else { return .failure(.message("\(name) isn't UTF-8, so it can't be changed.")) }
723 guard let (edit, start, level) = insert(into: state) else { return .failure(.message("Can't find \(parent.label) any more.")) }
724 try state.apply([edit], baseRevision: state.revision)
725 if case .conflict = try saver.save(&state, to: url) { return .failure(.message("\(name) changed on disk; nothing was added.")) }
726 return .success(target(start, level, FileRecord.hash(state.mergeBase)))
727 } catch {
728 return .failure(.message("Can't add \(title): \(error.localizedDescription)"))
729 }
730 }
731
732 public enum RefileFailure: Error, Equatable {
733 case message(String)
734 }
735
736 /// The edit `org-refile-new-child` makes in `text` under the heading at `start` (nil for
737 /// the file), and where the new heading starts and its level.
738 static func newChild(_ text: String, under start: Int??, title: String) -> (edit: TextEdit, start: Int, level: Int) {
739 let ns = text as NSString
740 var prefix = ""
741 var pos = ns.length
742 var level = 1
743 if case .some(.some(let heading)) = start {
744 var stars = 0
745 while heading + stars < ns.length, ns.character(at: heading + stars) == 42 { stars += 1 }
746 level = stars + 1
747 // `org-end-of-subtree t t`: the next heading at this level or above.
748 var at = NSMaxRange(ns.lineRange(for: NSRange(location: heading, length: 0)))
749 pos = ns.length
750 while at < ns.length {
751 let line = ns.lineRange(for: NSRange(location: at, length: 0))
752 var n = 0
753 while at + n < NSMaxRange(line), ns.character(at: at + n) == 42 { n += 1 }
754 if n > 0, n <= stars, at + n < ns.length, [32, 9].contains(ns.character(at: at + n)) {
755 pos = at
756 break
757 }
758 at = NSMaxRange(line)
759 }
760 } else if ns.length > 0, ns.character(at: ns.length - 1) != 10 {
761 prefix = "\n"
762 }
763 // `org-back-over-empty-lines`.
764 var back = pos
765 while back > 0, [32, 9, 10, 13].contains(ns.character(at: back - 1)) { back -= 1 }
766 var lineAfter = back
767 while lineAfter < ns.length, ns.character(at: lineAfter) != 10 { lineAfter += 1 }
768 if lineAfter < ns.length { lineAfter += 1 }
769 if !prefix.isEmpty { lineAfter = ns.length }
770 let at = min(lineAfter, pos)
771 let insertion = prefix + "\n" + String(repeating: "*", count: level) + " " + title + "\n"
772 let newStart = at + (prefix as NSString).length + 1
773 return (TextEdit(range: at..<at, replacement: insertion), newStart, level)
774 }
775
776 /// The file `archive(from:now:)` moves the entry to, or nil when it can't tell.
777 public func archiveFile(from: (path: String, offset: Int)? = nil, now: Date = Date()) -> String? {
778 guard let (path, context) = source(from, now: now), case .success(let destination) = Archive.destination(context, sourcePath: path) else { return nil }
779 return destination.path
780 }
781
782 /// Archives the subtree at the caret, or at `from`, where `org-archive-subtree` would.
783 /// Returns a message.
784 @discardableResult
785 public func archive(from: (path: String, offset: Int)? = nil, now: Date = Date()) -> String? {
786 guard let (path, context) = source(from, now: now) else { return from == nil ? nil : "Can't read the entry's file." }
787 let destination: Archive.Destination
788 switch Archive.destination(context, sourcePath: path) {
789 case .success(let value): destination = value
790 case .failure(.message(let message)): return message
791 }
792 // An archive file open in a buffer takes the subtree there.
793 if !destination.isSameFile, let open = entry(destination.path) {
794 let state = open.buffer.document
795 let name = (destination.path as NSString).lastPathComponent
796 guard state.isEditable else { return "\(name) isn't UTF-8, so it can't be changed." }
797 let edits: Archive.Edits
798 switch Archive.run(context, sourcePath: path, destination: destination, archiveText: state.text) {
799 case .success(let value): edits = value
800 case .failure(.message(let message)): return message
801 }
802 if let archiveEdit = edits.archive {
803 let edit = EditResult(baseRevision: state.revision, edits: [archiveEdit])
804 if case .failed(let message) = open.buffer.perform(PrecomputedEdit(edit), now: now, answers: [:]) { return message }
805 changed(open)
806 }
807 if let message = applySource(edits.source, path: path, now: now) { return message }
808 return "Archived to \(name)"
809 }
810 do {
811 let url = URL(fileURLWithPath: destination.path)
812 let existing = destination.isSameFile ? nil : try fileSystem.read(url)
813 var state = loaded(existing ?? [], path: url.path)
814 if !destination.isSameFile, !state.isEditable { return "\(url.lastPathComponent) isn't UTF-8, so it can't be changed." }
815 let edits: Archive.Edits
816 switch Archive.run(context, sourcePath: path, destination: destination, archiveText: existing.map { _ in state.text }) {
817 case .success(let value): edits = value
818 case .failure(.message(let message)): return message
819 }
820 if let archiveEdit = edits.archive {
821 try state.apply([archiveEdit], baseRevision: state.revision)
822 if case .conflict = try saver.save(&state, to: url) { return "\(url.lastPathComponent) changed on disk; nothing was archived." }
823 }
824 if let message = applySource(edits.source, path: path, now: now) { return message }
825 return destination.isSameFile ? "Archived under \(destination.heading ?? "the end of the file")" : "Archived to \(url.lastPathComponent)"
826 } catch {
827 return "Can't archive: \(error.localizedDescription)"
828 }
829 }
830
831 // MARK: - Commands from other views
832
833 /// Where the heading line `line` is now in `path`: at `offset` if it still reads so, else
834 /// the copy of the line nearest `offset`. For acting on agenda entries after other edits
835 /// moved them.
836 public func locateHeading(path: String, line: String, near offset: Int) -> Int? {
837 guard let text = entry(path)?.buffer.document.text ?? (try? fileSystem.read(URL(fileURLWithPath: path))).flatMap({ $0.map { SourceText(bytes: $0).text } }) else { return nil }
838 let ns = text as NSString
839 let length = (line as NSString).length
840 if offset + length <= ns.length, ns.substring(with: NSRange(location: offset, length: length)) == line,
841 offset == 0 || ns.character(at: offset - 1) == 10 {
842 return offset
843 }
844 var best: Int?
845 var search = NSRange(location: 0, length: ns.length)
846 while true {
847 let found = ns.range(of: line, options: [], range: search)
848 guard found.location != NSNotFound else { break }
849 let atLineStart = found.location == 0 || ns.character(at: found.location - 1) == 10
850 let lineEnd = NSMaxRange(found) == ns.length || ns.character(at: NSMaxRange(found)) == 10
851 if atLineStart, lineEnd, best.map({ abs($0 - offset) > abs(found.location - offset) }) ?? true { best = found.location }
852 search = NSRange(location: NSMaxRange(found), length: ns.length - NSMaxRange(found))
853 }
854 return best
855 }
856
857 /// Runs `command` with the caret at `offset` in the file at `path`, as the agenda does:
858 /// through the buffer when the file is open, leaving its caret alone; otherwise on the
859 /// file, written back at once through the save path. `expect` is the heading line the
860 /// caller saw at a position; if the text there changed, nothing runs.
861 public func perform(
862 _ command: any OrgCommand, path: String, at offset: Int, expect: (start: Int, line: String)?,
863 answers: [String: String] = [:], now: Date = Date()
864 ) -> CommandStep {
865 let stale = CommandStep.failed("The entry changed; the agenda has been refreshed.")
866 func matches(_ text: String) -> Bool {
867 guard let expect else { return true }
868 let ns = text as NSString
869 guard expect.start + (expect.line as NSString).length <= ns.length else { return false }
870 return ns.substring(with: NSRange(location: expect.start, length: (expect.line as NSString).length)) == expect.line
871 }
872 if let entry = entry(path) {
873 let buffer = entry.buffer
874 guard matches(buffer.document.text) else { return stale }
875 do {
876 let options = self.options
877 let step = try buffer.update { try $0.run(command, selection: [offset..<offset], now: now, answers: answers, options: options) }
878 if case .commit = step { changed(entry) }
879 return step
880 } catch {
881 return .failed("\(error)")
882 }
883 }
884 let url = URL(fileURLWithPath: path)
885 let name = url.lastPathComponent
886 do {
887 guard let bytes = try fileSystem.read(url) else { return .failed("\(name) no longer exists.") }
888 var state = loaded(bytes, path: path)
889 guard state.isEditable else { return .failed("\(name) isn't UTF-8, so it can't be changed.") }
890 guard matches(state.text) else { return stale }
891 let step = try state.run(command, selection: [offset..<offset], now: now, answers: answers, options: options)
892 if case .commit = step, state.isDirty, case .conflict = try saver.save(&state, to: url) {
893 return .failed("\(name) changed on disk; nothing was changed.")
894 }
895 if case .commit = step { textChanged?(path) }
896 return step
897 } catch {
898 return .failed("Can't change \(name): \(error.localizedDescription)")
899 }
900 }
901
902 /// Applies `edits`, computed against `expected`, to `path` as one change, as Replace in
903 /// Files and the renames do. An open buffer takes them as an edit its editor can undo; a
904 /// buffer with no editor yet, and a file that isn't open, first has its text kept in
905 /// recovery (labelled `replace`), and the file is written through the save path. Nil when
906 /// done, else why not; nothing changes when the text is no longer `expected`.
907 public func applyChanges(_ edits: [TextEdit], to path: String, expecting expected: String, now: Date = Date()) -> String? {
908 let url = URL(fileURLWithPath: path)
909 let name = url.lastPathComponent
910 let stale = "\(name) changed after the search; nothing was changed in it."
911 if let entry = entry(path) {
912 let state = entry.buffer.document
913 guard state.isEditable else { return "\(name) isn't UTF-8, so it can't be changed." }
914 guard state.text == expected else { return stale }
915 if entry.buffer is StateBuffer {
916 do { try recovery.keep(try state.encodedText(), for: url, label: "replace") } catch {
917 return "Can't keep a copy of \(name): \(error.localizedDescription)"
918 }
919 }
920 if case .failed(let message) = entry.buffer.perform(PrecomputedEdit(EditResult(baseRevision: state.revision, edits: edits)), now: now, answers: [:]) {
921 return message
922 }
923 changed(entry)
924 return nil
925 }
926 do {
927 guard let bytes = try fileSystem.read(url) else { return "\(name) no longer exists." }
928 var state = loaded(bytes, path: path)
929 guard state.isEditable else { return "\(name) isn't UTF-8, so it can't be changed." }
930 guard state.text == expected else { return stale }
931 try recovery.keep(bytes, for: url, label: "replace")
932 try state.apply(edits, baseRevision: state.revision)
933 if case .conflict = try saver.save(&state, to: url) { return "\(name) changed on disk; nothing was changed." }
934 textChanged?(path)
935 return nil
936 } catch {
937 return "Can't change \(name): \(error.localizedDescription)"
938 }
939 }
940
941 // MARK: - External work
942
943 /// Recalculates a table in Emacs from a snapshot of the buffer, then replaces the table
944 /// with Emacs's text if it hasn't changed meanwhile. Returns a message for the echo area.
945 public func recalculateInEmacs(table: Range<Int>, point: Int, form: String) async -> String {
946 guard let programs = Self.runner else {
947 #if os(macOS)
948 return "Tables that need Emacs aren't recalculated in this version of orgstar."
949 #else
950 return "Tables that need Emacs aren't recalculated on iOS."
951 #endif
952 }
953 guard let entry = current else { return "No file is open." }
954 let path = entry.path
955 let snapshot = entry.buffer.document.text as NSString
956 guard table.upperBound <= snapshot.length else { return "The table moved; try again." }
957 let old = snapshot.substring(with: NSRange(table))
958 let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
959 do {
960 let new = try await programs.recalculateTable(text: snapshot as String, directory: directory, table: table, point: point, form: form)
961 guard entries.contains(where: { $0 === entry }) else { return "The file was closed before Emacs finished." }
962 let current = entry.buffer
963 let text = current.document.text as NSString
964 guard table.upperBound <= text.length, text.substring(with: NSRange(table)) == old else {
965 return "The table changed while Emacs recalculated it; nothing was changed."
966 }
967 guard new != old else { return "Recalculated in Emacs" }
968 let result = EditResult(baseRevision: current.document.revision, edits: [TextEdit(range: table, replacement: new)])
969 if case .failed(let message) = current.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
970 changed(entry)
971 return "Recalculated in Emacs"
972 } catch is CancellationError {
973 return "Recalculation canceled"
974 } catch {
975 return "\(error)"
976 }
977 }
978
979 /// Runs a src block and writes its result under it, unless the block changed while it
980 /// ran. Returns a message for the echo area.
981 public func runBabel(_ job: BabelJob) async -> String {
982 guard let entry = current else { return "No file is open." }
983 let directory = URL(fileURLWithPath: entry.path).deletingLastPathComponent()
984 let programs = Self.runner
985 /// A program through `programs`; without it, Emacs Lisp in `Elisp` and js in
986 /// JavaScriptCore, and nothing else.
987 func run(_ job: BabelJob) async throws -> BabelOutput {
988 if let output = job.known { return output }
989 if let programs { return try await programs.runBabel(job, fileDirectory: directory) }
990 #if canImport(JavaScriptCore)
991 if let output = try await JavaScriptBlocks.run(job, directory: directory) { return output }
992 #endif
993 if job.calc != nil { return try TableReason.calcBlock(job) }
994 #if canImport(SQLite3)
995 if let output = try SQLiteBlocks.run(job, directory: directory) { return output }
996 #endif
997 #if canImport(WebKit)
998 if let output = try await DiagramBlocks.run(job, directory: directory) { return output }
999 #endif
1000 guard let output = try Babel.evaluateNatively(job) else {
1001 #if os(macOS)
1002 throw Babel.Failure.message(job.lispForm == nil
1003 ? "\(job.language) blocks don't run in this version of orgstar."
1004 : "This block uses Emacs Lisp that runs only in Emacs.")
1005 #else
1006 throw Babel.Failure.message(job.lispForm == nil
1007 ? "\(job.language) blocks need the Mac to run."
1008 : "This block uses Emacs Lisp that runs only in Emacs, on the Mac.")
1009 #endif
1010 }
1011 return output
1012 }
1013 /// Writes the result to `:file`, when the block asks for that; a message when it can't.
1014 func write(_ job: BabelJob, _ output: BabelOutput) -> String? {
1015 guard let file = Babel.fileResult(job, output: output) else { return nil }
1016 do {
1017 try file.contents.write(to: Self.resultFile(file.path, job: job, directory: directory), atomically: true, encoding: .utf8)
1018 return nil
1019 } catch {
1020 return "Can't write \(file.path): \(error.localizedDescription)"
1021 }
1022 }
1023 // Without programs, a block that refers to one that can't run here runs nothing.
1024 if programs == nil, !job.needs.isEmpty, let language = ([job.language] + job.referenced).first(where: { !Self.inProcess.contains($0) }) {
1025 #if os(macOS)
1026 return "This block needs a \(language) block, and \(language) blocks don't run in this version of orgstar; nothing was run."
1027 #else
1028 return "This block needs a \(language) block, and \(language) blocks need the Mac to run; nothing was run."
1029 #endif
1030 }
1031 do {
1032 // Blocks the `:var`s, `:post` and noweb references refer to run first, one at a time.
1033 // Each is one of the blocks agreed to, or the run stops: the text may have changed
1034 // while a block ran.
1035 var job = job
1036 let approved = job.approved
1037 func agreed(_ block: BabelJob) -> Bool { approved.isEmpty || approved.contains(block.blockText) }
1038 if job.needsFile {
1039 let document = entry.buffer.document
1040 switch Babel.replan(job, file: entry.path, text: document.text, tree: document.tree) {
1041 case .failure(.message(let message)): return message
1042 case .success(let next): job = next
1043 }
1044 }
1045 while let need = job.needs.first {
1046 guard agreed(need.job) else { return "The blocks changed while running; nothing more was run." }
1047 let output = try await run(need.job)
1048 guard entries.contains(where: { $0 === entry }) else { return "The file was closed before the block finished." }
1049 if let message = write(need.job, output) { return message }
1050 let document = entry.buffer.document
1051 switch Babel.resume(job, need: need, output: output, text: document.text, tree: document.tree) {
1052 case .failure(.message(let message)): return message
1053 case .success(let next): job = next
1054 }
1055 }
1056 guard agreed(job) else { return "The blocks changed while running; nothing more was run." }
1057 let output = try await run(job)
1058 guard entries.contains(where: { $0 === entry }) else { return "The file was closed before the block finished." }
1059 if let message = write(job, output) { return message }
1060 let current = entry.buffer
1061 let document = current.document
1062 let done = output.problem ?? "Code block evaluation complete."
1063 switch Babel.finish(job, output: output, text: document.text, settings: document.tree.settings) {
1064 case .failure(.message(let message)):
1065 return message
1066 case .success(let edits):
1067 guard !edits.isEmpty else { return job.finish.params.contains("silent") ? output.problem ?? output.stdout : done }
1068 let result = EditResult(baseRevision: document.revision, edits: edits)
1069 if case .failed(let message) = current.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
1070 changed(entry)
1071 return done
1072 }
1073 } catch is CancellationError {
1074 return "Code block canceled."
1075 } catch Babel.Failure.message(let message) {
1076 return message
1077 } catch {
1078 return "\(error)"
1079 }
1080 }
1081
1082 /// The languages that run without programs.
1083 static let inProcess: Set<String> = ["emacs-lisp", "elisp", "js", "javascript", "calc", "sqlite", "dot", "mermaid"]
1084
1085 /// Where a block's `:file` result goes: relative to `:dir`, itself relative to `directory`.
1086 static func resultFile(_ name: String, job: BabelJob, directory: URL) -> URL {
1087 let runDirectory = job.directory.map { URL(fileURLWithPath: $0, relativeTo: directory).standardizedFileURL } ?? directory
1088 return name.hasPrefix("/") ? URL(fileURLWithPath: name) : runDirectory.appendingPathComponent(name)
1089 }
1090
1091 /// The `:file` the block writes its result to, for the open file; nil without one.
1092 public func resultFile(of job: BabelJob) -> String? {
1093 guard let path, let name = job.finish.file else { return nil }
1094 return Self.resultFile(name, job: job, directory: URL(fileURLWithPath: path).deletingLastPathComponent()).path
1095 }
1096
1097 /// The block running now, to cancel.
1098 @ObservationIgnored private var babelTask: Task<String, Never>?
1099 public private(set) var isRunningBabel = false
1100
1101 /// Runs a src block in the background; its message comes back through `report`.
1102 public func startBabel(_ job: BabelJob, report: @escaping @MainActor (String) -> Void) {
1103 babelTask?.cancel()
1104 isRunningBabel = true
1105 let task = Task { await runBabel(job) }
1106 babelTask = task
1107 Task {
1108 let message = await task.value
1109 if babelTask == task {
1110 babelTask = nil
1111 isRunningBabel = false
1112 }
1113 report(message)
1114 }
1115 }
1116
1117 /// Stops the running block; its results aren't inserted.
1118 public func cancelBabel() {
1119 babelTask?.cancel()
1120 }
1121
1122 // MARK: - Locations
1123
1124 /// Opens the file of `location` if needed and asks the editor to show the heading. Offsets
1125 /// are used only if the buffer matches what was indexed; otherwise the heading is found
1126 /// again by position and title.
1127 public func show(_ location: HeadingLocation) {
1128 if path != location.path { open(location.path) }
1129 guard let document else { return }
1130 let hash = FileRecord.hash(document.mergeBase)
1131 let offset: Int
1132 if !isDirty, hash == location.contentHash {
1133 offset = location.start
1134 } else if location.ordinal == HeadingLocation.fileOrdinal {
1135 offset = 0
1136 } else if location.ordinal < outline.count, outline[location.ordinal].title == location.title {
1137 offset = outline[location.ordinal].start
1138 } else if let entry = outline.first(where: { $0.title == location.title }) {
1139 offset = entry.start
1140 } else {
1141 return
1142 }
1143 reveal(offset)
1144 }
1145
1146 /// Asks the focused pane's editor to show `offset`.
1147 public func reveal(_ offset: Int) {
1148 reveal(offset, in: focused)
1149 }
1150
1151 /// Asks `pane`'s editor to show `offset`.
1152 public func reveal(_ offset: Int, in pane: EditorPane) {
1153 requestID += 1
1154 pane.revealRequest = (offset, requestID)
1155 }
1156
1157 /// Called when the workspace sees a file change on disk: an open buffer of it takes the
1158 /// change in.
1159 public func fileChanged(_ path: String) {
1160 let interval = Perf.begin("session.fileChanged")
1161 defer { interval.end((path as NSString).lastPathComponent) }
1162 guard let entry = entry(path) else { return }
1163 let name = (path as NSString).lastPathComponent
1164 let read: [UInt8]?
1165 do {
1166 read = try fileSystem.read(URL(fileURLWithPath: path))
1167 } catch {
1168 showError(String(localized: "Couldn't Read File", comment: "Error alert title"), "Can't read \(name): \(error.localizedDescription)")
1169 return
1170 }
1171 guard let bytes = read else { return }
1172 let buffer = entry.buffer
1173 guard bytes != buffer.document.mergeBase else { return }
1174 switch buffer.update({ $0.diskChanged(to: bytes) }) {
1175 case .conflict:
1176 entry.autosave?.cancel()
1177 entry.conflict = "\(name) changed on disk, and the changes conflict with yours."
1178 case .merged, .reloaded:
1179 entry.conflict = nil
1180 resolveSetup(entry)
1181 // Edits merged with the disk's still need saving.
1182 scheduleAutosave(entry)
1183 case .unchanged:
1184 break
1185 }
1186 refresh(entry)
1187 }
1188}
1189
1190/// `base`, telling `written` about each file it replaced.
1191private struct WriteReporting: FileSystem {
1192 let base: FileSystem
1193 let written: @Sendable (URL) -> Void
1194
1195 func read(_ url: URL) throws -> [UInt8]? { try base.read(url) }
1196
1197 func replace(_ url: URL, with bytes: [UInt8]) throws -> [UInt8]? {
1198 let replaced = try base.replace(url, with: bytes)
1199 written(url)
1200 return replaced
1201 }
1202}