Sources/OrgApp/DocumentSession.swift
898 lines · 43992 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 /// A buffer for `bytes` read from `path`, with the keywords of the setup files it names.
81 func loaded(_ bytes: [UInt8], path: String) -> DocumentState {
82 DocumentState(bytes: bytes, defaults: defaults.resolvingSetupFiles(in: SourceText(bytes: bytes).text, path: path, read: readText))
83 }
84
85 /// The settings of the file at `path` as the editor sees them: its open buffer's, or its
86 /// text on disk with the defaults and the setup files it names.
87 public func settings(for path: String) -> OrgSettings? {
88 if let entry = entry(path) { return entry.buffer.document.tree.settings }
89 guard let bytes = (try? fileSystem.read(URL(fileURLWithPath: path))).flatMap({ $0 }) else { return nil }
90 return loaded(bytes, path: path).tree.settings
91 }
92
93 /// A file's text, for setup files.
94 func readText(_ file: String) -> String? {
95 (try? fileSystem.read(URL(fileURLWithPath: file))).flatMap { $0 }.flatMap { String(bytes: $0, encoding: .utf8) }
96 }
97
98 /// C-c C-c on a keyword line: the open file's setup files read again (`org-mode-restart`).
99 public func refreshSetup() {
100 guard let entry = current else { return }
101 resolveSetup(entry)
102 refresh()
103 editVersion += 1
104 }
105
106 /// The entry's setup files read again, as its text names them now.
107 private func resolveSetup(_ entry: Entry) {
108 let settings = defaults.resolvingSetupFiles(in: entry.buffer.document.text, path: entry.path, read: readText)
109 if settings != entry.buffer.document.defaults { entry.buffer.update { $0.setDefaults(settings) } }
110 }
111
112 /// One open file.
113 @MainActor
114 final class Entry {
115 let path: String
116 var buffer: DocumentBuffer
117 var conflict: String?
118 var autosave: Task<Void, Never>?
119
120 init(path: String, buffer: DocumentBuffer) {
121 self.path = path
122 self.buffer = buffer
123 }
124 }
125
126 private let fileSystem: FileSystem
127 private let recovery: RecoveryStore
128 @ObservationIgnored private var entries: [Entry] = []
129 @ObservationIgnored private var current: Entry?
130 /// Paths, most recently shown first.
131 @ObservationIgnored private var history: [String] = []
132 @ObservationIgnored private var outlineUpdate: Task<Void, Never>?
133 private var requestID = 0
134
135 public init(
136 fileSystem: FileSystem = CoordinatedFileSystem(),
137 recovery: RecoveryStore = FileRecoveryStore(directory: WorkspaceModel.defaultDirectory.appendingPathComponent("Recovery"))
138 ) {
139 self.fileSystem = fileSystem
140 self.recovery = recovery
141 }
142
143 private var buffer: DocumentBuffer? { current?.buffer }
144 /// The current buffer's pending autosave, for tests to wait on.
145 var autosave: Task<Void, Never>? { current?.autosave }
146 private var url: URL? { path.map { URL(fileURLWithPath: $0) } }
147 /// Whether the open file is an org file (`.org`, `.org_archive`), not plain text.
148 public var isOrg: Bool { path.map(Self.isOrgPath) ?? false }
149
150 public static func isOrgPath(_ path: String) -> Bool {
151 path.hasSuffix(".org") || path.hasSuffix(".org_archive")
152 }
153
154 /// The caret in the open file.
155 public var caret: Int { buffer?.selection.first?.lowerBound ?? 0 }
156 private var name: String { path.map { ($0 as NSString).lastPathComponent } ?? "" }
157
158 /// The open buffer of `path`, or of the same file by another path (`find-buffer-visiting`
159 /// by truename).
160 private func entry(_ path: String) -> Entry? {
161 if let exact = entries.first(where: { $0.path == path }) { return exact }
162 let truename = URL(fileURLWithPath: path).resolvingSymlinksInPath().path
163 return entries.first { URL(fileURLWithPath: $0.path).resolvingSymlinksInPath().path == truename }
164 }
165
166 /// The buffer's name as uniquify writes it (`post-forward-angle-brackets`): the file name,
167 /// with as many of its folders as tell it apart from other open files of the same name.
168 public func bufferName(_ path: String) -> String {
169 let name = (path as NSString).lastPathComponent
170 let others = openPaths.filter { $0 != path && ($0 as NSString).lastPathComponent == name }
171 guard !others.isEmpty else { return name }
172 func folders(_ p: String) -> [String] { (p as NSString).deletingLastPathComponent.split(separator: "/").map(String.init).reversed() }
173 let mine = folders(path)
174 var count = 1
175 while count < mine.count, others.contains(where: { folders($0).prefix(count) == mine.prefix(count) }) { count += 1 }
176 return name + "<" + mine.prefix(count).reversed().joined(separator: "/") + ">"
177 }
178
179 public func isOpen(_ path: String) -> Bool { entry(path) != nil }
180
181 /// The caret of an open file.
182 public func caret(of path: String) -> Int? { entry(path)?.buffer.selection.first?.lowerBound }
183
184 /// The text of every open file, for views that read files (the agenda, search).
185 public var openDocuments: [(path: String, document: DocumentState)] {
186 entries.map { ($0.path, $0.buffer.document) }
187 }
188
189 /// The text of every open file by path, for the agenda.
190 public var openTexts: [String: String] {
191 Dictionary(entries.map { ($0.path, $0.buffer.document.text) }, uniquingKeysWith: { a, _ in a })
192 }
193
194 /// Open buffers, most recently shown first.
195 public var recentPaths: [String] { history.filter(isOpen) }
196
197 /// Shows the buffer of `path`, opening the file if it isn't open.
198 public func open(_ path: String) {
199 let interval = Perf.begin("session.open")
200 defer { interval.end((path as NSString).lastPathComponent) }
201 if let existing = entry(path) {
202 activate(existing)
203 return
204 }
205 do {
206 guard let bytes = try fileSystem.read(URL(fileURLWithPath: path)) else {
207 lastError = "\((path as NSString).lastPathComponent) no longer exists."
208 return
209 }
210 let entry = Entry(path: path, buffer: StateBuffer(loaded(bytes, path: path)))
211 let index = current.flatMap { c in entries.firstIndex { $0 === c } }.map { $0 + 1 } ?? entries.count
212 entries.insert(entry, at: index)
213 activate(entry)
214 } catch {
215 lastError = "Can't open \(path): \(error.localizedDescription)"
216 }
217 }
218
219 private func activate(_ entry: Entry) {
220 current = entry
221 path = entry.path
222 conflict = entry.conflict
223 revealRequest = nil
224 history.removeAll { $0 == entry.path }
225 history.insert(entry.path, at: 0)
226 refresh()
227 }
228
229 /// The buffer before or after the current one, wrapping.
230 public func cycle(_ step: Int) {
231 guard let current, let index = entries.firstIndex(where: { $0 === current }), entries.count > 1 else { return }
232 activate(entries[((index + step) % entries.count + entries.count) % entries.count])
233 }
234
235 /// The buffer shown before the current one.
236 public func showPrevious() {
237 guard let previous = recentPaths.dropFirst().first else { return }
238 open(previous)
239 }
240
241 /// Closes the buffer of `path` without saving it; the most recent other buffer shows.
242 public func kill(_ path: String) {
243 guard let entry = entry(path) else { return }
244 entry.autosave?.cancel()
245 entries.removeAll { $0 === entry }
246 history.removeAll { $0 == path }
247 if entry === current {
248 current = nil
249 if let next = recentPaths.first.flatMap(self.entry) ?? entries.last {
250 activate(next)
251 } else {
252 outlineUpdate?.cancel()
253 self.path = nil
254 document = nil
255 outline = []
256 isDirty = false
257 conflict = nil
258 revealRequest = nil
259 refreshLists()
260 }
261 } else {
262 refreshLists()
263 }
264 }
265
266 /// Closes the current buffer without saving, as when its file was deleted.
267 public func close() {
268 if let path { kill(path) }
269 }
270
271 /// Makes `buffer`, built from `document`, the live state of the current file.
272 public func attach(_ buffer: DocumentBuffer) {
273 current?.buffer = buffer
274 refresh()
275 }
276
277 /// The buffer of `path` changed in its editor: the current one updates its views, another
278 /// saves on its own.
279 public func bufferChanged(_ path: String) {
280 guard let entry = entry(path) else { return }
281 if entry === current { bufferChanged() } else { scheduleAutosave(entry); refreshLists() }
282 }
283
284 /// The buffer changed through typing. The outline follows once typing pauses.
285 public func bufferChanged() {
286 refresh(outline: false)
287 outlineUpdate?.cancel()
288 outlineUpdate = Task { [weak self] in
289 try? await Task.sleep(for: .milliseconds(300))
290 guard !Task.isCancelled, let self, let document = self.document else { return }
291 self.outline = self.isOrg ? Presentation.outline(document.tree) : []
292 self.editVersion += 1
293 }
294 if let current { scheduleAutosave(current) }
295 }
296
297 private func refresh(outline updateOutline: Bool = true) {
298 let interval = Perf.begin("session.refresh")
299 defer { interval.end() }
300 refreshLists()
301 guard let buffer else { return }
302 let state = buffer.document
303 document = state
304 if isDirty != state.isDirty { isDirty = state.isDirty }
305 if isReadOnly == state.isEditable { isReadOnly = !state.isEditable }
306 if conflict != current?.conflict { conflict = current?.conflict }
307 if updateOutline {
308 outline = isOrg ? Presentation.outline(state.tree) : []
309 editVersion += 1
310 }
311 }
312
313 private func refreshLists() {
314 let paths = entries.map(\.path)
315 if paths != openPaths { openPaths = paths }
316 let dirty = Set(entries.filter { $0.buffer.document.isDirty }.map(\.path))
317 if dirty != dirtyPaths { dirtyPaths = dirty }
318 }
319
320 // MARK: - Saving
321
322 private var saver: Saver { Saver(fileSystem: fileSystem, recovery: recovery) }
323
324 private func scheduleAutosave(_ entry: Entry) {
325 entry.autosave?.cancel()
326 guard saveMode == .automatic, entry.buffer.document.isDirty, entry.conflict == nil else { return }
327 entry.autosave = Task { [weak self, weak entry, autosaveDelay] in
328 try? await Task.sleep(for: autosaveDelay)
329 guard !Task.isCancelled, let self, let entry else { return }
330 self.save(entry)
331 }
332 }
333
334 /// Saves the current buffer now. True when nothing is left unsaved.
335 @discardableResult
336 public func save() -> Bool {
337 guard let current else { return true }
338 return save(current)
339 }
340
341 /// Saves the buffer of `path`. True when nothing is left unsaved.
342 @discardableResult
343 public func save(_ path: String) -> Bool {
344 guard let entry = entry(path) else { return true }
345 return save(entry)
346 }
347
348 /// Saves every open buffer. True when nothing is left unsaved.
349 @discardableResult
350 public func saveAll() -> Bool {
351 entries.map { save($0) }.allSatisfy { $0 }
352 }
353
354 @discardableResult
355 private func save(_ entry: Entry) -> Bool {
356 let interval = Perf.begin("session.save")
357 defer { interval.end((entry.path as NSString).lastPathComponent) }
358 entry.autosave?.cancel()
359 let name = (entry.path as NSString).lastPathComponent
360 guard entry.buffer.document.isDirty else { return true }
361 guard entry.conflict == nil else { return false }
362 do {
363 let outcome = try entry.buffer.update { try saver.save(&$0, to: URL(fileURLWithPath: entry.path)) }
364 switch outcome {
365 case .saved, .mergedAndSaved:
366 break
367 case .conflict:
368 entry.conflict = "\(name) changed on disk, and the changes conflict with yours."
369 case .overwroteExternalChange(let change), .changedAfterWrite(let change):
370 if case .conflict = change {
371 entry.conflict = "\(name) changed on disk while saving, and the changes conflict with yours."
372 }
373 }
374 } catch {
375 lastError = "Can't save \(name): \(error.localizedDescription)"
376 }
377 if entry === current { refresh() } else { refreshLists() }
378 return !entry.buffer.document.isDirty
379 }
380
381 /// Resolves a conflict by writing the buffer over the disk version, which goes to recovery.
382 public func keepMine() {
383 guard let buffer, let url else { return }
384 do {
385 try buffer.update { try saver.overwrite(&$0, to: url) }
386 current?.conflict = nil
387 } catch {
388 lastError = "Can't save \(name): \(error.localizedDescription)"
389 }
390 refresh()
391 }
392
393 /// Resolves a conflict by loading the disk version; the buffer goes to recovery.
394 public func useDiskVersion() {
395 guard let buffer, let url else { return }
396 do {
397 guard let bytes = try fileSystem.read(url) else { return }
398 if isDirty { try recovery.keep(try buffer.document.encodedText(), for: url, label: "local") }
399 let path = url.path
400 buffer.update { $0 = loaded(bytes, path: path) }
401 current?.conflict = nil
402 } catch {
403 lastError = "Can't read \(name): \(error.localizedDescription)"
404 }
405 refresh()
406 }
407
408 // MARK: - Comparing versions
409
410 /// The buffer, the file on disk and the version both started from, while they conflict.
411 public func conflictVersions() -> (mine: String, disk: String, base: String)? {
412 guard current?.conflict != nil, let buffer, let url, let disk = try? fileSystem.read(url) else { return nil }
413 return (buffer.document.text, SourceText(bytes: disk).text, SourceText(bytes: buffer.document.mergeBase).text)
414 }
415
416 /// Resolves a conflict as `git merge` leaves one: the buffer holds both sides' changes, those
417 /// that conflict between markers, to fix and save. The disk version becomes the base, and
418 /// the buffer as it was goes to recovery.
419 public func mergeConflictWithMarkers() {
420 guard let versions = conflictVersions(), let buffer, let url, let disk = try? fileSystem.read(url) else { return }
421 do {
422 try recovery.keep(try buffer.document.encodedText(), for: url, label: "local")
423 let merged = mergeWithMarkers(base: versions.base, ours: versions.mine, theirs: versions.disk, oursLabel: "yours", theirsLabel: "disk")
424 try buffer.update { state in
425 state = loaded(disk, path: url.path)
426 try state.apply(lineEdits(from: versions.disk, to: merged), baseRevision: state.revision)
427 }
428 current?.conflict = nil
429 } catch {
430 lastError = "Can't merge \(name): \(error.localizedDescription)"
431 }
432 refresh()
433 }
434
435 /// Syncthing's conflict copies of the open file beside it: `name.sync-conflict-DATE-TIME-ID.ext`.
436 public func syncConflictCopies() -> [URL] {
437 guard let url else { return [] }
438 let folder = url.deletingLastPathComponent()
439 let stem = NSRegularExpression.escapedPattern(for: url.deletingPathExtension().lastPathComponent)
440 let ext = url.pathExtension.isEmpty ? "" : "\\." + NSRegularExpression.escapedPattern(for: url.pathExtension)
441 let pattern = "^" + stem + "\\.sync-conflict-[0-9]{8}-[0-9]{6}-[A-Z0-9]+" + ext + "$"
442 let names = (try? FileManager.default.contentsOfDirectory(atPath: folder.path)) ?? []
443 return names.filter { $0.range(of: pattern, options: .regularExpression) != nil }.sorted().map { folder.appendingPathComponent($0) }
444 }
445
446 /// What to do with a conflict copy: keep the file as it is, take the copy's text, or merge
447 /// the two with markers. The copy goes to recovery and is removed.
448 public enum CopyResolution { case keepFile, useCopy, merge }
449
450 public func resolve(copy: URL, _ resolution: CopyResolution) -> String? {
451 guard let buffer, let url else { return "No file is open" }
452 do {
453 guard let bytes = try fileSystem.read(copy) else { return "\(copy.lastPathComponent) is gone" }
454 let copyText = SourceText(bytes: bytes).text
455 let mine = buffer.document.text
456 let new: String? = switch resolution {
457 case .keepFile: nil
458 case .useCopy: copyText
459 case .merge: mergeWithMarkers(base: nil, ours: mine, theirs: copyText, oursLabel: url.lastPathComponent, theirsLabel: copy.lastPathComponent)
460 }
461 if let new, new != mine {
462 let result = EditResult(baseRevision: buffer.document.revision, edits: lineEdits(from: mine, to: new))
463 if case .failed(let message) = buffer.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
464 }
465 try recovery.keep(bytes, for: url, label: "sync-conflict")
466 try FileManager.default.removeItem(at: copy)
467 } catch {
468 return "Can't resolve \(copy.lastPathComponent): \(error.localizedDescription)"
469 }
470 if let current { changed(current) }
471 return nil
472 }
473
474 /// Versions of the open file kept in recovery, newest first, with when and why each was
475 /// kept.
476 public func recoveryVersions() -> [(url: URL, date: Date, label: String)] {
477 guard let url, let store = recovery as? FileRecoveryStore, let versions = try? store.versions(for: url) else { return [] }
478 // `STAMP-LABEL-UUID8-NAME`, as `FileRecoveryStore.keep` names them.
479 return versions.reversed().map { version in
480 let m = version.lastPathComponent.firstMatch(of: /^([0-9]+)-(.+?)-([0-9A-Fa-f]{8})-/)
481 let nanos = m.flatMap { UInt64($0.1) } ?? 0
482 return (version, Date(timeIntervalSince1970: Double(nanos) / 1_000_000_000), m.map { String($0.2) } ?? "")
483 }
484 }
485
486 /// The text of a kept version.
487 public func recoveryText(_ version: URL) -> String? {
488 (try? fileSystem.read(version)).flatMap { $0 }.map { SourceText(bytes: $0).text }
489 }
490
491 /// Puts a kept version's text in the buffer, as an edit that can be undone; the buffer as it
492 /// was goes to recovery.
493 public func restore(_ version: URL) -> String? {
494 guard let buffer, let url, let text = recoveryText(version) else { return "Can't read that version" }
495 do {
496 try recovery.keep(try buffer.document.encodedText(), for: url, label: "local")
497 } catch {
498 return "Can't keep the current version: \(error.localizedDescription)"
499 }
500 let mine = buffer.document.text
501 let result = EditResult(baseRevision: buffer.document.revision, edits: lineEdits(from: mine, to: text))
502 if case .failed(let message) = buffer.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
503 if let current { changed(current) }
504 return nil
505 }
506
507 // MARK: - Moving subtrees
508
509 /// The current context of the buffer, as commands see it.
510 private func editContext(now: Date) -> EditContext? {
511 guard let buffer else { return nil }
512 let document = buffer.document
513 return EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: buffer.selection, now: now, options: options)
514 }
515
516 /// The file and context a subtree command works on: `from` (a file and a heading in it,
517 /// as the agenda gives them), or the current buffer at its caret.
518 private func source(_ from: (path: String, offset: Int)?, now: Date) -> (path: String, context: EditContext)? {
519 guard let from else {
520 guard let path, let context = editContext(now: now) else { return nil }
521 return (path, context)
522 }
523 let state: DocumentState
524 if let open = entry(from.path) {
525 state = open.buffer.document
526 } else {
527 guard let bytes = try? fileSystem.read(URL(fileURLWithPath: from.path)) else { return nil }
528 state = loaded(bytes, path: from.path)
529 }
530 guard state.isEditable else { return nil }
531 let context = EditContext(revision: state.revision, text: state.text, tree: state.tree, selection: [from.offset..<from.offset], now: now, options: options)
532 return (from.path, context)
533 }
534
535 /// Applies an edit computed from `source(_:now:)` to that file, open or not.
536 private func applySource(_ edit: EditResult, path: String, now: Date) -> String? {
537 if case .failed(let message) = perform(PrecomputedEdit(edit), path: path, at: 0, expect: nil, now: now) { return message }
538 return nil
539 }
540
541 /// Moves the subtree at the caret, or at `from`, under `target`. For another file, that
542 /// file is written first, through the save path; the subtree leaves its file only once it
543 /// has. Returns a message for the echo area.
544 @discardableResult
545 public func refile(to target: RefileTarget, from: (path: String, offset: Int)? = nil, now: Date = Date()) -> String? {
546 guard let (path, context) = source(from, now: now) else { return from == nil ? nil : "Can't read the entry's file." }
547 if target.path == path {
548 let answers = ["refile": target.start.map(String.init) ?? ""]
549 let step = from == nil ? buffer?.perform(RefileWithinFile(), now: now, answers: answers)
550 : perform(RefileWithinFile(), path: path, at: from!.offset, expect: nil, answers: answers, now: now)
551 if case .failed(let message)? = step { return message }
552 if from == nil { bufferChanged() }
553 return "Refiled to \(target.label)"
554 }
555 let url = URL(fileURLWithPath: target.path)
556 let targetName = (target.path as NSString).lastPathComponent
557 // A target open in a buffer takes the subtree there, with its unsaved edits.
558 if let open = entry(target.path) {
559 let state = open.buffer.document
560 guard state.isEditable else { return "\(targetName) isn't UTF-8, so it can't be changed." }
561 guard let start = target.locate(in: state) else { return "Can't find \(target.label) any more." }
562 guard let result = Refile.toOtherFile(source: context, target: state.text, under: start) else { return "Can't refile from here." }
563 let edit = EditResult(baseRevision: state.revision, edits: [result.target])
564 if case .failed(let message) = open.buffer.perform(PrecomputedEdit(edit), now: now, answers: [:]) { return message }
565 changed(open)
566 if let message = applySource(result.source, path: path, now: now) { return message }
567 return "Refiled to \(target.label)"
568 }
569 do {
570 guard let bytes = try fileSystem.read(url) else { return "\(targetName) no longer exists." }
571 var state = loaded(bytes, path: url.path)
572 guard state.isEditable else { return "\(targetName) isn't UTF-8, so it can't be changed." }
573 guard let start = target.locate(in: state) else { return "Can't find \(target.label) any more." }
574 guard let result = Refile.toOtherFile(source: context, target: state.text, under: start) else { return "Can't refile from here." }
575 try state.apply([result.target], baseRevision: state.revision)
576 if case .conflict = try saver.save(&state, to: url) { return "\(targetName) changed on disk; nothing was refiled." }
577 if let message = applySource(result.source, path: path, now: now) { return message }
578 return "Refiled to \(target.label)"
579 } catch {
580 return "Can't refile: \(error.localizedDescription)"
581 }
582 }
583
584 /// Archives the subtree at the caret, or at `from`, where `org-archive-subtree` would.
585 /// Returns a message.
586 @discardableResult
587 public func archive(from: (path: String, offset: Int)? = nil, now: Date = Date()) -> String? {
588 guard let (path, context) = source(from, now: now) else { return from == nil ? nil : "Can't read the entry's file." }
589 let destination: Archive.Destination
590 switch Archive.destination(context, sourcePath: path) {
591 case .success(let value): destination = value
592 case .failure(.message(let message)): return message
593 }
594 // An archive file open in a buffer takes the subtree there.
595 if !destination.isSameFile, let open = entry(destination.path) {
596 let state = open.buffer.document
597 let name = (destination.path as NSString).lastPathComponent
598 guard state.isEditable else { return "\(name) isn't UTF-8, so it can't be changed." }
599 let edits: Archive.Edits
600 switch Archive.run(context, sourcePath: path, destination: destination, archiveText: state.text) {
601 case .success(let value): edits = value
602 case .failure(.message(let message)): return message
603 }
604 if let archiveEdit = edits.archive {
605 let edit = EditResult(baseRevision: state.revision, edits: [archiveEdit])
606 if case .failed(let message) = open.buffer.perform(PrecomputedEdit(edit), now: now, answers: [:]) { return message }
607 changed(open)
608 }
609 if let message = applySource(edits.source, path: path, now: now) { return message }
610 return "Archived to \(name)"
611 }
612 do {
613 let url = URL(fileURLWithPath: destination.path)
614 let existing = destination.isSameFile ? nil : try fileSystem.read(url)
615 var state = loaded(existing ?? [], path: url.path)
616 if !destination.isSameFile, !state.isEditable { return "\(url.lastPathComponent) isn't UTF-8, so it can't be changed." }
617 let edits: Archive.Edits
618 switch Archive.run(context, sourcePath: path, destination: destination, archiveText: existing.map { _ in state.text }) {
619 case .success(let value): edits = value
620 case .failure(.message(let message)): return message
621 }
622 if let archiveEdit = edits.archive {
623 try state.apply([archiveEdit], baseRevision: state.revision)
624 if case .conflict = try saver.save(&state, to: url) { return "\(url.lastPathComponent) changed on disk; nothing was archived." }
625 }
626 if let message = applySource(edits.source, path: path, now: now) { return message }
627 return destination.isSameFile ? "Archived under \(destination.heading ?? "the end of the file")" : "Archived to \(url.lastPathComponent)"
628 } catch {
629 return "Can't archive: \(error.localizedDescription)"
630 }
631 }
632
633 // MARK: - Commands from other views
634
635 /// Where the heading line `line` is now in `path`: at `offset` if it still reads so, else
636 /// the copy of the line nearest `offset`. For acting on agenda entries after other edits
637 /// moved them.
638 public func locateHeading(path: String, line: String, near offset: Int) -> Int? {
639 guard let text = entry(path)?.buffer.document.text ?? (try? fileSystem.read(URL(fileURLWithPath: path))).flatMap({ $0.map { SourceText(bytes: $0).text } }) else { return nil }
640 let ns = text as NSString
641 let length = (line as NSString).length
642 if offset + length <= ns.length, ns.substring(with: NSRange(location: offset, length: length)) == line,
643 offset == 0 || ns.character(at: offset - 1) == 10 {
644 return offset
645 }
646 var best: Int?
647 var search = NSRange(location: 0, length: ns.length)
648 while true {
649 let found = ns.range(of: line, options: [], range: search)
650 guard found.location != NSNotFound else { break }
651 let atLineStart = found.location == 0 || ns.character(at: found.location - 1) == 10
652 let lineEnd = NSMaxRange(found) == ns.length || ns.character(at: NSMaxRange(found)) == 10
653 if atLineStart, lineEnd, best.map({ abs($0 - offset) > abs(found.location - offset) }) ?? true { best = found.location }
654 search = NSRange(location: NSMaxRange(found), length: ns.length - NSMaxRange(found))
655 }
656 return best
657 }
658
659 /// Runs `command` with the caret at `offset` in the file at `path`, as the agenda does:
660 /// through the buffer when the file is open, leaving its caret alone; otherwise on the
661 /// file, written back at once through the save path. `expect` is the heading line the
662 /// caller saw at a position; if the text there changed, nothing runs.
663 public func perform(
664 _ command: any OrgCommand, path: String, at offset: Int, expect: (start: Int, line: String)?,
665 answers: [String: String] = [:], now: Date = Date()
666 ) -> CommandStep {
667 let stale = CommandStep.failed("The entry changed; the agenda has been refreshed.")
668 func matches(_ text: String) -> Bool {
669 guard let expect else { return true }
670 let ns = text as NSString
671 guard expect.start + (expect.line as NSString).length <= ns.length else { return false }
672 return ns.substring(with: NSRange(location: expect.start, length: (expect.line as NSString).length)) == expect.line
673 }
674 if let entry = entry(path) {
675 let buffer = entry.buffer
676 guard matches(buffer.document.text) else { return stale }
677 do {
678 let options = self.options
679 let step = try buffer.update { try $0.run(command, selection: [offset..<offset], now: now, answers: answers, options: options) }
680 if case .commit = step {
681 if entry === current { bufferChanged() } else { scheduleAutosave(entry); refreshLists() }
682 }
683 return step
684 } catch {
685 return .failed("\(error)")
686 }
687 }
688 let url = URL(fileURLWithPath: path)
689 let name = url.lastPathComponent
690 do {
691 guard let bytes = try fileSystem.read(url) else { return .failed("\(name) no longer exists.") }
692 var state = loaded(bytes, path: path)
693 guard state.isEditable else { return .failed("\(name) isn't UTF-8, so it can't be changed.") }
694 guard matches(state.text) else { return stale }
695 let step = try state.run(command, selection: [offset..<offset], now: now, answers: answers, options: options)
696 if case .commit = step, state.isDirty, case .conflict = try saver.save(&state, to: url) {
697 return .failed("\(name) changed on disk; nothing was changed.")
698 }
699 return step
700 } catch {
701 return .failed("Can't change \(name): \(error.localizedDescription)")
702 }
703 }
704
705 // MARK: - External work
706
707 /// Recalculates a table in Emacs from a snapshot of the buffer, then replaces the table
708 /// with Emacs's text if it hasn't changed meanwhile. Returns a message for the echo area.
709 public func recalculateInEmacs(table: Range<Int>, point: Int, form: String) async -> String {
710 #if os(macOS)
711 guard let entry = current else { return "No file is open." }
712 let path = entry.path
713 let snapshot = entry.buffer.document.text as NSString
714 guard table.upperBound <= snapshot.length else { return "The table moved; try again." }
715 let old = snapshot.substring(with: NSRange(table))
716 let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
717 do {
718 let new = try await EmacsRunner.recalculateTable(text: snapshot as String, directory: directory, table: table, point: point, form: form)
719 guard entries.contains(where: { $0 === entry }) else { return "The file was closed before Emacs finished." }
720 let current = entry.buffer
721 let text = current.document.text as NSString
722 guard table.upperBound <= text.length, text.substring(with: NSRange(table)) == old else {
723 return "The table changed while Emacs recalculated it; nothing was changed."
724 }
725 guard new != old else { return "Recalculated in Emacs" }
726 let result = EditResult(baseRevision: current.document.revision, edits: [TextEdit(range: table, replacement: new)])
727 if case .failed(let message) = current.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
728 changed(entry)
729 return "Recalculated in Emacs"
730 } catch is CancellationError {
731 return "Recalculation canceled"
732 } catch {
733 return "\(error)"
734 }
735 #else
736 return "Tables that need Emacs aren't recalculated on iOS."
737 #endif
738 }
739
740 /// Runs a src block and writes its result under it, unless the block changed while it
741 /// ran. Returns a message for the echo area.
742 public func runBabel(_ job: BabelJob) async -> String {
743 guard let entry = current else { return "No file is open." }
744 let directory = URL(fileURLWithPath: entry.path).deletingLastPathComponent()
745 /// A program on the Mac; on iOS, Emacs Lisp in `Elisp`, and nothing else.
746 func run(_ job: BabelJob) async throws -> BabelOutput {
747 #if os(macOS)
748 return try await BabelRunner.run(job, fileDirectory: directory)
749 #else
750 guard let output = try Babel.evaluateNatively(job) else {
751 throw Babel.Failure.message(job.lispForm == nil
752 ? "\(job.language) blocks need the Mac to run."
753 : "This block uses Emacs Lisp that runs only in Emacs, on the Mac.")
754 }
755 return output
756 #endif
757 }
758 do {
759 // Blocks the `:var`s refer to run first, one at a time.
760 // Each is one of the blocks agreed to, or the run stops: the text may have changed
761 // while a block ran.
762 var job = job
763 let approved = job.approved
764 func agreed(_ block: BabelJob) -> Bool { approved.isEmpty || approved.contains(block.blockText) }
765 if job.needsFile {
766 let document = entry.buffer.document
767 switch Babel.replan(job, file: entry.path, text: document.text, tree: document.tree) {
768 case .failure(.message(let message)): return message
769 case .success(let next): job = next
770 }
771 }
772 while let need = job.needs.first {
773 guard agreed(need.job) else { return "The blocks changed while running; nothing more was run." }
774 let output = try await run(need.job)
775 guard entries.contains(where: { $0 === entry }) else { return "The file was closed before the block finished." }
776 let document = entry.buffer.document
777 switch Babel.resume(job, need: need, output: output, text: document.text, tree: document.tree) {
778 case .failure(.message(let message)): return message
779 case .success(let next): job = next
780 }
781 }
782 guard agreed(job) else { return "The blocks changed while running; nothing more was run." }
783 let output = try await run(job)
784 guard entries.contains(where: { $0 === entry }) else { return "The file was closed before the block finished." }
785 if let file = Babel.fileResult(job, output: output) {
786 let runDirectory = job.directory.map { URL(fileURLWithPath: $0, relativeTo: directory).standardizedFileURL } ?? directory
787 let target = file.path.hasPrefix("/") ? URL(fileURLWithPath: file.path) : runDirectory.appendingPathComponent(file.path)
788 do {
789 try file.contents.write(to: target, atomically: true, encoding: .utf8)
790 } catch {
791 return "Can't write \(file.path): \(error.localizedDescription)"
792 }
793 }
794 let current = entry.buffer
795 let document = current.document
796 let done = output.problem ?? "Code block evaluation complete."
797 switch Babel.finish(job, output: output, text: document.text, settings: document.tree.settings) {
798 case .failure(.message(let message)):
799 return message
800 case .success(let edits):
801 guard !edits.isEmpty else { return job.finish.params.contains("silent") ? output.problem ?? output.stdout : done }
802 let result = EditResult(baseRevision: document.revision, edits: edits)
803 if case .failed(let message) = current.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
804 changed(entry)
805 return done
806 }
807 } catch is CancellationError {
808 return "Code block canceled."
809 } catch Babel.Failure.message(let message) {
810 return message
811 } catch {
812 return "\(error)"
813 }
814 }
815
816 /// The block running now, to cancel.
817 @ObservationIgnored private var babelTask: Task<String, Never>?
818 public private(set) var isRunningBabel = false
819
820 /// Runs a src block in the background; its message comes back through `report`.
821 public func startBabel(_ job: BabelJob, report: @escaping @MainActor (String) -> Void) {
822 babelTask?.cancel()
823 isRunningBabel = true
824 let task = Task { await runBabel(job) }
825 babelTask = task
826 Task {
827 let message = await task.value
828 if babelTask == task {
829 babelTask = nil
830 isRunningBabel = false
831 }
832 report(message)
833 }
834 }
835
836 /// Stops the running block; its results aren't inserted.
837 public func cancelBabel() {
838 babelTask?.cancel()
839 }
840
841 /// A buffer changed outside typing: the current one updates its views, another saves.
842 private func changed(_ entry: Entry) {
843 if entry === current { bufferChanged() } else { scheduleAutosave(entry); refreshLists() }
844 }
845
846 // MARK: - Locations
847
848 /// Opens the file of `location` if needed and asks the editor to show the heading. Offsets
849 /// are used only if the buffer matches what was indexed; otherwise the heading is found
850 /// again by position and title.
851 public func show(_ location: HeadingLocation) {
852 if path != location.path { open(location.path) }
853 guard let document else { return }
854 let hash = FileRecord.hash(document.mergeBase)
855 let offset: Int
856 if !isDirty, hash == location.contentHash {
857 offset = location.start
858 } else if location.ordinal == HeadingLocation.fileOrdinal {
859 offset = 0
860 } else if location.ordinal < outline.count, outline[location.ordinal].title == location.title {
861 offset = outline[location.ordinal].start
862 } else if let entry = outline.first(where: { $0.title == location.title }) {
863 offset = entry.start
864 } else {
865 return
866 }
867 reveal(offset)
868 }
869
870 public func reveal(_ offset: Int) {
871 requestID += 1
872 revealRequest = (offset, requestID)
873 }
874
875 /// Called when the workspace sees a file change on disk: an open buffer of it takes the
876 /// change in.
877 public func fileChanged(_ path: String) {
878 let interval = Perf.begin("session.fileChanged")
879 defer { interval.end((path as NSString).lastPathComponent) }
880 guard let entry = entry(path), let bytes = try? fileSystem.read(URL(fileURLWithPath: path)) else { return }
881 let buffer = entry.buffer
882 guard bytes != buffer.document.mergeBase else { return }
883 let name = (path as NSString).lastPathComponent
884 switch buffer.update({ $0.diskChanged(to: bytes) }) {
885 case .conflict:
886 entry.autosave?.cancel()
887 entry.conflict = "\(name) changed on disk, and the changes conflict with yours."
888 case .merged, .reloaded:
889 entry.conflict = nil
890 resolveSetup(entry)
891 // Edits merged with the disk's still need saving.
892 scheduleAutosave(entry)
893 case .unchanged:
894 break
895 }
896 if entry === current { refresh() } else { refreshLists() }
897 }
898}