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