Sources/OrgApp/DocumentSession.swift
1360 lines · 68127 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 /// Files and recovery through `crypt`, and as they are on disk.
141 private let fileSystem: FileSystem
142 private let recovery: RecoveryStore
143 private let diskFileSystem: FileSystem
144 private let diskRecovery: RecoveryStore
145 /// Passphrases and encrypted entries of the open files.
146 @ObservationIgnored public let crypt = CryptVault()
147 @ObservationIgnored private var entries: [Entry] = []
148 /// The focused pane's buffer.
149 private var current: Entry? { focused.path.flatMap(entry) }
150 /// Paths, most recently shown first, across every pane.
151 @ObservationIgnored private var history: [String] = []
152 @ObservationIgnored private var outlineUpdates: [String: Task<Void, Never>] = [:]
153 private var requestID = 0
154
155 public init(
156 fileSystem: FileSystem = CoordinatedFileSystem(),
157 recovery: RecoveryStore = FileRecoveryStore(directory: WorkspaceModel.defaultDirectory.appendingPathComponent("Recovery"))
158 ) {
159 diskFileSystem = fileSystem
160 diskRecovery = recovery
161 self.fileSystem = CryptFileSystem(base: fileSystem, vault: crypt)
162 self.recovery = CryptRecoveryStore(base: recovery, vault: crypt)
163 let pane = EditorPane()
164 panes = [pane]
165 focused = pane
166 crypt.written = { [weak self] path in
167 if Thread.isMainThread {
168 MainActor.assumeIsolated { self?.fileSaved?(path) }
169 } else {
170 Task { @MainActor in self?.fileSaved?(path) }
171 }
172 }
173 }
174
175 // MARK: - Encryption
176
177 /// Called with a file's path each time the session wrote it to disk: a buffer saved (by
178 /// hand or on its own), Keep Mine, and refile, archive or agenda changes to files that
179 /// aren't open. Not called for a save that was held, failed or conflicted.
180 @ObservationIgnored public var fileSaved: ((String) -> Void)?
181
182 /// `org-crypt-use-before-save-magic`: entries with `cryptTag` are encrypted on every save.
183 public var encryptsTaggedEntries: Bool {
184 get { crypt.encryptsTaggedEntries }
185 set { crypt.encryptsTaggedEntries = newValue }
186 }
187
188 /// `org-crypt-tag-matcher`.
189 public var cryptTag: String {
190 get { crypt.tag }
191 set { crypt.tag = newValue }
192 }
193
194 /// Open files that aren't saved until a passphrase is given: tagged entries that would be
195 /// written unencrypted, or an encrypted file without one. Other edits to them wait too.
196 public private(set) var held: [String: CryptHold] = [:]
197
198 /// An encrypted file waiting for its passphrase to open, and the pane to show it in.
199 public private(set) var unlockRequest: String?
200 @ObservationIgnored private var unlockPane: EditorPane?
201
202 /// The passphrase remembered in the Keychain, after Touch ID, Face ID or the device's
203 /// password; nil when there's none or it wasn't given.
204 @ObservationIgnored public var storedPassphrase: (String) async -> String? = { await CryptPassphrases.stored(for: $0) }
205 @ObservationIgnored public var hasStoredPassphrase: (String) -> Bool = { CryptPassphrases.hasStored($0) }
206 /// Files whose remembered passphrase is being asked for, and those where it was refused:
207 /// the Keychain is asked once per file until the file closes or Encrypt is chosen.
208 @ObservationIgnored private var askingKeychain: Set<String> = []
209 @ObservationIgnored private var refusedKeychain: Set<String> = []
210
211 public static func isEncryptedFile(_ path: String) -> Bool { CryptVault.isEncryptedFile(path) }
212
213 /// An encrypted org file, which lists with the org files.
214 public static func isEncryptedOrgFile(_ path: String) -> Bool { path.hasSuffix(".org.gpg") }
215
216 /// Gives `passphrase` for `path`: an encrypted file opens with it, and a held file is saved.
217 /// It must open the file, or the file's encrypted entries if it has any. A message when it
218 /// doesn't.
219 public func unlock(_ passphrase: String, for path: String) -> String? {
220 if let entry = entry(path) {
221 if let message = OrgCrypt.firstMessage(entry.buffer.document.text), !OrgCrypt.opens(message, passphrase: passphrase) {
222 return String(localized: "Wrong passphrase")
223 }
224 // An encrypted file on disk keeps its passphrase: a passphrase given after Forget
225 // must open it.
226 if Self.isEncryptedFile(entry.path), let disk = try? diskFileSystem.read(URL(fileURLWithPath: entry.path)),
227 !CryptVault.opens(disk, passphrase: passphrase) {
228 return String(localized: "Wrong passphrase")
229 }
230 crypt.unlock(passphrase, for: entry.path)
231 refusedKeychain.remove(entry.path)
232 save(entry)
233 return nil
234 }
235 guard Self.isEncryptedFile(path) else { return nil }
236 let bytes: [UInt8]
237 do {
238 guard let read = try diskFileSystem.read(URL(fileURLWithPath: path)) else { return "\((path as NSString).lastPathComponent) no longer exists." }
239 bytes = read
240 } catch {
241 return error.localizedDescription
242 }
243 guard CryptVault.opens(bytes, passphrase: passphrase) else { return String(localized: "Wrong passphrase") }
244 crypt.unlock(passphrase, for: path)
245 let pane = unlockPane.flatMap { pane in panes.contains { $0 === pane } ? pane : nil } ?? focused
246 unlockRequest = nil
247 unlockPane = nil
248 open(path, in: pane)
249 return nil
250 }
251
252 /// The encrypted file waiting for its passphrase stays closed.
253 public func cancelUnlock() {
254 unlockRequest = nil
255 unlockPane = nil
256 }
257
258 /// A crypt command used `passphrase` for `path`: saves use it from now on, without asking.
259 public func cryptUsed(_ passphrase: String, for path: String) {
260 crypt.unlock(passphrase, for: path)
261 refusedKeychain.remove(path)
262 }
263
264 /// The entry holding `plaintext` in `path`'s buffer was decrypted from `message`.
265 public func cryptDecrypted(message: String, plaintext: String, for path: String) {
266 crypt.remember(message: message, plaintext: plaintext, for: path)
267 }
268
269 /// Forget Encryption Passphrase: the passphrase leaves the Keychain and the session.
270 public func forgetPassphrase(for path: String) {
271 CryptPassphrases.forget(path)
272 crypt.forgetPassphrase(for: path)
273 }
274
275 /// Whether `path`'s buffer is held back from disk now.
276 private func updateHold(_ entry: Entry) -> CryptHold? {
277 let hold = entry.buffer.document.isDirty ? crypt.hold(entry.buffer.document.text, for: entry.path) : nil
278 if held[entry.path] != hold { held[entry.path] = hold }
279 return hold
280 }
281
282 /// Asks the Keychain for `entry`'s passphrase, once, and saves with it.
283 private func askKeychain(_ entry: Entry) {
284 let path = entry.path
285 guard !askingKeychain.contains(path), !refusedKeychain.contains(path), hasStoredPassphrase(path) else { return }
286 askingKeychain.insert(path)
287 Task { [weak self, weak entry] in
288 guard let self else { return }
289 let passphrase = await self.storedPassphrase(path)
290 self.askingKeychain.remove(path)
291 guard let entry, self.entries.contains(where: { $0 === entry }) else { return }
292 if let passphrase, self.unlock(passphrase, for: path) == nil { return }
293 self.refusedKeychain.insert(path)
294 }
295 }
296
297 // MARK: - Panes
298
299 /// A new, empty pane.
300 public func makePane() -> EditorPane {
301 let pane = EditorPane()
302 panes.append(pane)
303 return pane
304 }
305
306 /// Removes `pane`; its buffers stay open. The last pane stays.
307 public func closePane(_ pane: EditorPane) {
308 guard panes.count > 1, let index = panes.firstIndex(where: { $0 === pane }) else { return }
309 panes.remove(at: index)
310 if focused === pane { focused = panes[0] }
311 }
312
313 /// The panes showing `path`.
314 private func panes(showing path: String) -> [EditorPane] {
315 panes.filter { $0.path == path }
316 }
317
318 private var buffer: DocumentBuffer? { current?.buffer }
319 /// The focused buffer's pending autosave, for tests to wait on.
320 var autosave: Task<Void, Never>? { current?.autosave }
321 private var url: URL? { path.map { URL(fileURLWithPath: $0) } }
322 /// Whether the open file is an org file (`.org`, `.org_archive`), not plain text.
323 public var isOrg: Bool { path.map(Self.isOrgPath) ?? false }
324
325 public static func isOrgPath(_ path: String) -> Bool {
326 path.hasSuffix(".org") || path.hasSuffix(".org_archive") || path.hasSuffix(".org.gpg")
327 }
328
329 /// The caret in the open file.
330 public var caret: Int { buffer?.selection.first?.lowerBound ?? 0 }
331 private var name: String { path.map { ($0 as NSString).lastPathComponent } ?? "" }
332
333 /// The open buffer of `path`, or of the same file by another path (`find-buffer-visiting`
334 /// by truename).
335 private func entry(_ path: String) -> Entry? {
336 if let exact = entries.first(where: { $0.path == path }) { return exact }
337 let truename = URL(fileURLWithPath: path).resolvingSymlinksInPath().path
338 return entries.first { URL(fileURLWithPath: $0.path).resolvingSymlinksInPath().path == truename }
339 }
340
341 /// The text of `path`: its buffer's when it's open, else what's on disk.
342 public func text(of path: String) -> String? {
343 if let entry = entry(path) { return entry.buffer.document.text }
344 guard let bytes = try? fileSystem.read(URL(fileURLWithPath: path)) else { return nil }
345 let state = loaded(bytes, path: path)
346 return state.isEditable ? state.text : nil
347 }
348
349 /// A copy of `path`'s text and tree, its buffer's when it's open, for changes made apart
350 /// and written back with `ReplaceChangedText`.
351 public func copy(of path: String) -> DocumentState? {
352 if let entry = entry(path) { return entry.buffer.document }
353 guard let bytes = try? fileSystem.read(URL(fileURLWithPath: path)) else { return nil }
354 let state = loaded(bytes, path: path)
355 return state.isEditable ? state : nil
356 }
357
358 /// The buffer's name as uniquify writes it (`post-forward-angle-brackets`): the file name,
359 /// with as many of its folders as tell it apart from other open files of the same name.
360 public func bufferName(_ path: String) -> String {
361 let name = (path as NSString).lastPathComponent
362 let others = openPaths.filter { $0 != path && ($0 as NSString).lastPathComponent == name }
363 guard !others.isEmpty else { return name }
364 func folders(_ p: String) -> [String] { (p as NSString).deletingLastPathComponent.split(separator: "/").map(String.init).reversed() }
365 let mine = folders(path)
366 var count = 1
367 while count < mine.count, others.contains(where: { folders($0).prefix(count) == mine.prefix(count) }) { count += 1 }
368 return name + "<" + mine.prefix(count).reversed().joined(separator: "/") + ">"
369 }
370
371 public func isOpen(_ path: String) -> Bool { entry(path) != nil }
372
373 /// The document of an open file, whichever pane shows it.
374 public func document(of path: String) -> DocumentState? { entry(path)?.buffer.document }
375
376 /// Whether `buffer` is the live state of `path`, as `attach` made it.
377 public func isAttached(_ buffer: DocumentBuffer, for path: String) -> Bool { entry(path)?.buffer === buffer }
378
379 /// The caret of an open file.
380 public func caret(of path: String) -> Int? { entry(path)?.buffer.selection.first?.lowerBound }
381
382 /// The text of every open file, for views that read files (the agenda, search).
383 public var openDocuments: [(path: String, document: DocumentState)] {
384 entries.map { ($0.path, $0.buffer.document) }
385 }
386
387 /// The text of every open file by path, for the agenda and what it writes (widgets, the
388 /// watch, reminders). Encrypted files, and files with entries decrypted that saving
389 /// encrypts, are left out: those views read them from disk.
390 public var openTexts: [String: String] {
391 let shown = entries.filter { !crypt.isPrivate($0.buffer.document.text, for: $0.path) }
392 return Dictionary(shown.map { ($0.path, $0.buffer.document.text) }, uniquingKeysWith: { a, _ in a })
393 }
394
395 /// Open buffers, most recently shown first.
396 public var recentPaths: [String] { history.filter(isOpen) }
397
398 /// Shows the buffer of `path` in the focused pane, opening the file if it isn't open.
399 public func open(_ path: String) {
400 open(path, in: focused)
401 }
402
403 /// Shows the buffer of `path` in `pane`, opening the file if it isn't open.
404 public func open(_ path: String, in pane: EditorPane) {
405 let interval = Perf.begin("session.open")
406 defer { interval.end((path as NSString).lastPathComponent) }
407 if let existing = entry(path) {
408 show(existing, in: pane)
409 return
410 }
411 if Self.isEncryptedFile(path), crypt.passphrase(for: path) == nil,
412 (try? diskFileSystem.read(URL(fileURLWithPath: path)))??.isEmpty == false {
413 unlockRequest = path
414 unlockPane = pane
415 return
416 }
417 do {
418 guard let bytes = try fileSystem.read(URL(fileURLWithPath: path)) else {
419 showError(String(localized: "Couldn't Open File", comment: "Error alert title"), "\((path as NSString).lastPathComponent) no longer exists.")
420 return
421 }
422 let entry = Entry(path: path, buffer: StateBuffer(loaded(bytes, path: path)))
423 let index = pane.path.flatMap(self.entry).flatMap { c in entries.firstIndex { $0 === c } }.map { $0 + 1 } ?? entries.count
424 entries.insert(entry, at: index)
425 show(entry, in: pane)
426 } catch {
427 showError(String(localized: "Couldn't Open File", comment: "Error alert title"), "Can't open \(path): \(error.localizedDescription)")
428 }
429 }
430
431 private func show(_ entry: Entry, in pane: EditorPane) {
432 pane.path = entry.path
433 if !pane.shown.contains(entry.path) { pane.shown.append(entry.path) }
434 pane.history.removeAll { $0 == entry.path }
435 pane.history.insert(entry.path, at: 0)
436 pane.revealRequest = nil
437 history.removeAll { $0 == entry.path }
438 history.insert(entry.path, at: 0)
439 refresh(pane)
440 }
441
442 /// The buffer before or after the focused one, wrapping, in the focused pane.
443 public func cycle(_ step: Int) {
444 guard let current, let index = entries.firstIndex(where: { $0 === current }), entries.count > 1 else { return }
445 show(entries[((index + step) % entries.count + entries.count) % entries.count], in: focused)
446 }
447
448 /// The buffer shown before the focused one.
449 public func showPrevious() {
450 guard let previous = recentPaths.dropFirst().first else { return }
451 open(previous)
452 }
453
454 /// Closes the buffer of `path` without saving it. A pane showing it shows the buffer it
455 /// showed before, else the most recent other buffer, else nothing.
456 public func kill(_ path: String) {
457 guard let entry = entry(path) else { return }
458 entry.autosave?.cancel()
459 entries.removeAll { $0 === entry }
460 crypt.close(entry.path)
461 held[entry.path] = nil
462 refusedKeychain.remove(entry.path)
463 history.removeAll { $0 == path }
464 outlineUpdates[path]?.cancel()
465 outlineUpdates[path] = nil
466 for pane in panes {
467 pane.shown.removeAll { $0 == path }
468 pane.history.removeAll { $0 == path }
469 guard pane.path == path else { continue }
470 if let next = pane.history.first.flatMap(self.entry) ?? recentPaths.first.flatMap(self.entry) ?? entries.last {
471 show(next, in: pane)
472 } else {
473 pane.path = nil
474 pane.outline = []
475 pane.isDirty = false
476 pane.isReadOnly = false
477 pane.conflict = nil
478 pane.revealRequest = nil
479 }
480 }
481 refreshLists()
482 }
483
484 /// Closes the focused buffer without saving, as when its file was deleted.
485 public func close() {
486 if let path { kill(path) }
487 }
488
489 /// Makes `buffer`, built from `document`, the live state of the focused file.
490 public func attach(_ buffer: DocumentBuffer) {
491 if let path { attach(buffer, for: path) }
492 }
493
494 /// Makes `buffer`, built from the file's `document`, the live state of `path`.
495 public func attach(_ buffer: DocumentBuffer, for path: String) {
496 guard let entry = entry(path) else { return }
497 entry.buffer = buffer
498 for pane in panes(showing: path) { refresh(pane) }
499 }
500
501 /// The buffer of `path` changed in its editor: the panes showing it update their views
502 /// once typing pauses, and it saves on its own.
503 public func bufferChanged(_ path: String) {
504 guard let entry = entry(path) else { return }
505 changed(entry)
506 }
507
508 /// The focused buffer changed through typing.
509 public func bufferChanged() {
510 if let current { changed(current) }
511 }
512
513 /// A buffer changed, typed or not: the panes showing it update their views, the outline
514 /// once typing pauses, and it saves on its own.
515 private func changed(_ entry: Entry) {
516 let showing = panes(showing: entry.path)
517 for pane in showing { refresh(pane, outline: false) }
518 outlineUpdates[entry.path]?.cancel()
519 if !showing.isEmpty {
520 let path = entry.path
521 outlineUpdates[path] = Task { [weak self, weak entry] in
522 try? await Task.sleep(for: .milliseconds(300))
523 guard !Task.isCancelled, let self, let entry else { return }
524 let outline = Self.isOrgPath(path) ? Presentation.outline(entry.buffer.document.tree) : []
525 for pane in self.panes(showing: path) {
526 pane.outline = outline
527 pane.editVersion += 1
528 }
529 }
530 }
531 scheduleAutosave(entry)
532 refreshLists()
533 textChanged?(entry.path)
534 }
535
536 /// `pane`'s view of its buffer, from the buffer's state.
537 private func refresh(_ pane: EditorPane, outline updateOutline: Bool = true) {
538 let interval = Perf.begin("session.refresh")
539 defer { interval.end() }
540 refreshLists()
541 guard let entry = pane.path.flatMap(entry) else { return }
542 let state = entry.buffer.document
543 if pane.isDirty != state.isDirty { pane.isDirty = state.isDirty }
544 if pane.isReadOnly == state.isEditable { pane.isReadOnly = !state.isEditable }
545 if pane.conflict != entry.conflict { pane.conflict = entry.conflict }
546 if updateOutline {
547 pane.outline = Self.isOrgPath(entry.path) ? Presentation.outline(state.tree) : []
548 pane.editVersion += 1
549 }
550 }
551
552 /// Every pane showing `entry`, from the buffer's state.
553 private func refresh(_ entry: Entry) {
554 for pane in panes(showing: entry.path) { refresh(pane) }
555 }
556
557 /// The focused pane, from its buffer's state.
558 private func refresh() {
559 refresh(focused)
560 }
561
562 private func refreshLists() {
563 let paths = entries.map(\.path)
564 if paths != openPaths { openPaths = paths }
565 let dirty = Set(entries.filter { $0.buffer.document.isDirty }.map(\.path))
566 if dirty != dirtyPaths { dirtyPaths = dirty }
567 }
568
569 // MARK: - Saving
570
571 private var saver: Saver {
572 Saver(fileSystem: WriteReporting(base: fileSystem) { [weak self] url in MainActor.assumeIsolated { self?.fileWritten?(url.path) } }, recovery: recovery)
573 }
574
575 private func scheduleAutosave(_ entry: Entry) {
576 entry.autosave?.cancel()
577 // A held file whose edits were undone, or whose tagged entries went, isn't held.
578 if held[entry.path] != nil, updateHold(entry) == nil { refresh(entry) }
579 guard saveMode == .automatic, entry.buffer.document.isDirty, entry.conflict == nil else { return }
580 entry.autosave = Task { [weak self, weak entry, autosaveDelay] in
581 try? await Task.sleep(for: autosaveDelay)
582 guard !Task.isCancelled, let self, let entry else { return }
583 self.save(entry)
584 }
585 }
586
587 /// Saves the current buffer now. True when nothing is left unsaved.
588 @discardableResult
589 public func save() -> Bool {
590 guard let current else { return true }
591 return save(current)
592 }
593
594 /// Saves the buffer of `path`. True when nothing is left unsaved.
595 @discardableResult
596 public func save(_ path: String) -> Bool {
597 guard let entry = entry(path) else { return true }
598 return save(entry)
599 }
600
601 /// Saves every open buffer. True when nothing is left unsaved.
602 @discardableResult
603 public func saveAll() -> Bool {
604 entries.map { save($0) }.allSatisfy { $0 }
605 }
606
607 @discardableResult
608 private func save(_ entry: Entry) -> Bool {
609 let interval = Perf.begin("session.save")
610 defer { interval.end((entry.path as NSString).lastPathComponent) }
611 entry.autosave?.cancel()
612 let name = (entry.path as NSString).lastPathComponent
613 guard updateHold(entry) == nil else {
614 askKeychain(entry)
615 refresh(entry)
616 return false
617 }
618 guard entry.buffer.document.isDirty else { return true }
619 guard entry.conflict == nil else { return false }
620 do {
621 let outcome = try entry.buffer.update { try saver.save(&$0, to: URL(fileURLWithPath: entry.path)) }
622 switch outcome {
623 case .saved, .mergedAndSaved:
624 break
625 case .conflict:
626 entry.conflict = "\(name) changed on disk, and the changes conflict with yours."
627 case .overwroteExternalChange(let change), .changedAfterWrite(let change):
628 if case .conflict = change {
629 entry.conflict = "\(name) changed on disk while saving, and the changes conflict with yours."
630 }
631 }
632 } catch {
633 showError(String(localized: "Couldn't Save File", comment: "Error alert title"), "Can't save \(name): \(error.localizedDescription)")
634 }
635 refresh(entry)
636 return !entry.buffer.document.isDirty
637 }
638
639 /// Resolves a conflict by writing the buffer over the disk version, which goes to recovery.
640 public func keepMine() {
641 guard let buffer, let url else { return }
642 if let current, updateHold(current) != nil { return refresh() }
643 do {
644 try buffer.update { try saver.overwrite(&$0, to: url) }
645 current?.conflict = nil
646 } catch {
647 showError(String(localized: "Couldn't Save File", comment: "Error alert title"), "Can't save \(name): \(error.localizedDescription)")
648 }
649 refresh()
650 }
651
652 /// Resolves a conflict by loading the disk version; the buffer goes to recovery.
653 public func useDiskVersion() {
654 guard let buffer, let url else { return }
655 do {
656 guard let bytes = try fileSystem.read(url) else { return }
657 if isDirty { try recovery.keep(try buffer.document.encodedText(), for: url, label: "local") }
658 let path = url.path
659 buffer.update { $0 = loaded(bytes, path: path) }
660 current?.conflict = nil
661 } catch {
662 showError(String(localized: "Couldn't Read File", comment: "Error alert title"), "Can't read \(name): \(error.localizedDescription)")
663 }
664 refresh()
665 }
666
667 // MARK: - Comparing versions
668
669 /// The buffer, the file on disk and the version both started from, while they conflict.
670 public func conflictVersions() -> (mine: String, disk: String, base: String)? {
671 guard current?.conflict != nil, let buffer, let url, let disk = try? fileSystem.read(url) else { return nil }
672 return (buffer.document.text, SourceText(bytes: disk).text, SourceText(bytes: buffer.document.mergeBase).text)
673 }
674
675 /// Resolves a conflict as `git merge` leaves one: the buffer holds both sides' changes, those
676 /// that conflict between markers, to fix and save. The disk version becomes the base, and
677 /// the buffer as it was goes to recovery.
678 public func mergeConflictWithMarkers() {
679 guard let versions = conflictVersions(), let buffer, let url, let disk = try? fileSystem.read(url) else { return }
680 do {
681 try recovery.keep(try buffer.document.encodedText(), for: url, label: "local")
682 let merged = mergeWithMarkers(base: versions.base, ours: versions.mine, theirs: versions.disk, oursLabel: "yours", theirsLabel: "disk")
683 try buffer.update { state in
684 state = loaded(disk, path: url.path)
685 try state.apply(lineEdits(from: versions.disk, to: merged), baseRevision: state.revision)
686 }
687 current?.conflict = nil
688 } catch {
689 showError(String(localized: "Couldn't Merge", comment: "Error alert title"), "Can't merge \(name): \(error.localizedDescription)")
690 }
691 refresh()
692 }
693
694 /// Syncthing's conflict copies of the open file beside it: `name.sync-conflict-DATE-TIME-ID.ext`.
695 public func syncConflictCopies() -> [URL] {
696 guard let url else { return [] }
697 let folder = url.deletingLastPathComponent()
698 let stem = NSRegularExpression.escapedPattern(for: url.deletingPathExtension().lastPathComponent)
699 let ext = url.pathExtension.isEmpty ? "" : "\\." + NSRegularExpression.escapedPattern(for: url.pathExtension)
700 let pattern = "^" + stem + "\\.sync-conflict-[0-9]{8}-[0-9]{6}-[A-Z0-9]+" + ext + "$"
701 let names = (try? FileManager.default.contentsOfDirectory(atPath: folder.path)) ?? []
702 return names.filter { $0.range(of: pattern, options: .regularExpression) != nil }.sorted().map { folder.appendingPathComponent($0) }
703 }
704
705 /// What to do with a conflict copy: keep the file as it is, take the copy's text, or merge
706 /// the two with markers. The copy goes to recovery and is removed.
707 public enum CopyResolution { case keepFile, useCopy, merge }
708
709 public func resolve(copy: URL, _ resolution: CopyResolution) -> String? {
710 guard let buffer, let url else { return "No file is open" }
711 do {
712 guard let bytes = try diskFileSystem.read(copy).map({ try crypt.plain($0, for: url.path) }) else { return "\(copy.lastPathComponent) is gone" }
713 let copyText = SourceText(bytes: bytes).text
714 let mine = buffer.document.text
715 let new: String? = switch resolution {
716 case .keepFile: nil
717 case .useCopy: copyText
718 case .merge: mergeWithMarkers(base: nil, ours: mine, theirs: copyText, oursLabel: url.lastPathComponent, theirsLabel: copy.lastPathComponent)
719 }
720 if let new, new != mine {
721 let result = EditResult(baseRevision: buffer.document.revision, edits: lineEdits(from: mine, to: new))
722 if case .failed(let message) = buffer.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
723 }
724 try recovery.keep(bytes, for: url, label: "sync-conflict")
725 try FileManager.default.removeItem(at: copy)
726 } catch {
727 return "Can't resolve \(copy.lastPathComponent): \(error.localizedDescription)"
728 }
729 if let current { changed(current) }
730 return nil
731 }
732
733 /// Versions of the open file kept in recovery, newest first, with when and why each was
734 /// kept.
735 public func recoveryVersions() -> [(url: URL, date: Date, label: String)] {
736 guard let url, let store = diskRecovery as? FileRecoveryStore, let versions = try? store.versions(for: url) else { return [] }
737 // `STAMP-LABEL-UUID8-NAME`, as `FileRecoveryStore.keep` names them.
738 return versions.reversed().map { version in
739 let m = version.lastPathComponent.firstMatch(of: /^([0-9]+)-(.+?)-([0-9A-Fa-f]{8})-/)
740 let nanos = m.flatMap { UInt64($0.1) } ?? 0
741 return (version, Date(timeIntervalSince1970: Double(nanos) / 1_000_000_000), m.map { String($0.2) } ?? "")
742 }
743 }
744
745 /// The text of a kept version.
746 public func recoveryText(_ version: URL) -> String? {
747 guard let bytes = (try? diskFileSystem.read(version)).flatMap({ $0 }) else { return nil }
748 // Kept as the open file is: encrypted with its passphrase, its entries' messages known.
749 return (try? path.map { try crypt.plain(bytes, for: $0) } ?? bytes).map { SourceText(bytes: $0).text }
750 }
751
752 /// Puts a kept version's text in the buffer, as an edit that can be undone; the buffer as it
753 /// was goes to recovery.
754 public func restore(_ version: URL) -> String? {
755 guard let text = recoveryText(version) else { return "Can't read that version" }
756 return restore(text: text)
757 }
758
759 /// Puts `text`, an earlier version of the file, in the buffer as an edit that can be undone;
760 /// the buffer as it was goes to recovery.
761 public func restore(text: String) -> String? {
762 guard let buffer, let url else { return "Can't read that version" }
763 do {
764 try recovery.keep(try buffer.document.encodedText(), for: url, label: "local")
765 } catch {
766 return "Can't keep the current version: \(error.localizedDescription)"
767 }
768 let mine = buffer.document.text
769 let result = EditResult(baseRevision: buffer.document.revision, edits: lineEdits(from: mine, to: text))
770 if case .failed(let message) = buffer.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
771 if let current { changed(current) }
772 return nil
773 }
774
775 // MARK: - Moving subtrees
776
777 /// The current context of the buffer, as commands see it.
778 private func editContext(now: Date) -> EditContext? {
779 guard let buffer else { return nil }
780 let document = buffer.document
781 return EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: buffer.selection, now: now, options: options)
782 }
783
784 /// The file and context a subtree command works on: `from` (a file and a heading in it,
785 /// as the agenda gives them), or the current buffer at its caret.
786 private func source(_ from: (path: String, offset: Int)?, now: Date) -> (path: String, context: EditContext)? {
787 guard let from else {
788 guard let path, let context = editContext(now: now) else { return nil }
789 return (path, context)
790 }
791 let state: DocumentState
792 if let open = entry(from.path) {
793 state = open.buffer.document
794 } else {
795 guard let bytes = try? fileSystem.read(URL(fileURLWithPath: from.path)) else { return nil }
796 state = loaded(bytes, path: from.path)
797 }
798 guard state.isEditable else { return nil }
799 let context = EditContext(revision: state.revision, text: state.text, tree: state.tree, selection: [from.offset..<from.offset], now: now, options: options)
800 return (from.path, context)
801 }
802
803 /// Applies an edit computed from `source(_:now:)` to that file, open or not.
804 private func applySource(_ edit: EditResult, path: String, now: Date) -> String? {
805 if case .failed(let message) = perform(PrecomputedEdit(edit), path: path, at: 0, expect: nil, now: now) { return message }
806 return nil
807 }
808
809 /// Moves the subtree at the caret, or at `from`, under `target`, or with `keep` copies it
810 /// there (`org-copy`). For another file, that file is written first, through the save
811 /// path; the subtree leaves its file only once it has. Returns a message for the echo area.
812 @discardableResult
813 public func refile(to target: RefileTarget, from: (path: String, offset: Int)? = nil, keep: Bool = false, now: Date = Date()) -> String? {
814 guard let (path, context) = source(from, now: now) else { return from == nil ? nil : "Can't read the entry's file." }
815 let done = (keep ? "Copied to " : "Refiled to ") + target.label
816 if target.path == path {
817 let answers = ["refile": target.start.map(String.init) ?? ""]
818 let command = RefileWithinFile(keep: keep)
819 let step = from == nil ? buffer?.perform(command, now: now, answers: answers)
820 : perform(command, path: path, at: from!.offset, expect: nil, answers: answers, now: now)
821 if case .failed(let message)? = step { return message }
822 if from == nil { bufferChanged() }
823 return done
824 }
825 let url = URL(fileURLWithPath: target.path)
826 let targetName = (target.path as NSString).lastPathComponent
827 // A target open in a buffer takes the subtree there, with its unsaved edits.
828 if let open = entry(target.path) {
829 let state = open.buffer.document
830 guard state.isEditable else { return "\(targetName) isn't UTF-8, so it can't be changed." }
831 guard let start = target.locate(in: state) else { return "Can't find \(target.label) any more." }
832 guard let result = Refile.toOtherFile(source: context, target: state.text, under: start, keep: keep) else { return "Can't refile from here." }
833 let edit = EditResult(baseRevision: state.revision, edits: [result.target])
834 if case .failed(let message) = open.buffer.perform(PrecomputedEdit(edit), now: now, answers: [:]) { return message }
835 changed(open)
836 if !keep, let message = applySource(result.source, path: path, now: now) { return message }
837 return done
838 }
839 do {
840 guard let bytes = try fileSystem.read(url) else { return "\(targetName) no longer exists." }
841 var state = loaded(bytes, path: url.path)
842 guard state.isEditable else { return "\(targetName) isn't UTF-8, so it can't be changed." }
843 guard let start = target.locate(in: state) else { return "Can't find \(target.label) any more." }
844 guard let result = Refile.toOtherFile(source: context, target: state.text, under: start, keep: keep) else { return "Can't refile from here." }
845 try state.apply([result.target], baseRevision: state.revision)
846 if case .conflict = try saver.save(&state, to: url) { return "\(targetName) changed on disk; nothing was refiled." }
847 if !keep, let message = applySource(result.source, path: path, now: now) { return message }
848 return done
849 } catch {
850 return "Can't refile: \(error.localizedDescription)"
851 }
852 }
853
854 /// `org-refile-new-child`: a heading `title` at the end of `parent`'s subtree, one level
855 /// below it, or at the end of the file for a file target. Returns the new heading as a
856 /// target, or a message.
857 public func createRefileChild(under parent: RefileTarget, title: String, now: Date = Date()) -> Result<RefileTarget, RefileFailure> {
858 let name = (parent.path as NSString).lastPathComponent
859 func insert(into state: DocumentState) -> (edit: TextEdit, start: Int, level: Int)? {
860 guard let start = parent.locate(in: state) else { return nil }
861 return Self.newChild(state.text, under: start, title: title)
862 }
863 func target(_ start: Int, _ level: Int, _ hash: String) -> RefileTarget {
864 RefileTarget(label: parent.label + "/" + title, path: parent.path, start: start, title: title, level: level, contentHash: hash)
865 }
866 if let open = entry(parent.path) {
867 let state = open.buffer.document
868 guard state.isEditable else { return .failure(.message("\(name) isn't UTF-8, so it can't be changed.")) }
869 guard let (edit, start, level) = insert(into: state) else { return .failure(.message("Can't find \(parent.label) any more.")) }
870 if case .failed(let message) = open.buffer.perform(PrecomputedEdit(EditResult(baseRevision: state.revision, edits: [edit])), now: now, answers: [:]) {
871 return .failure(.message(message))
872 }
873 changed(open)
874 return .success(target(start, level, ""))
875 }
876 do {
877 let url = URL(fileURLWithPath: parent.path)
878 guard let bytes = try fileSystem.read(url) else { return .failure(.message("\(name) no longer exists.")) }
879 var state = loaded(bytes, path: url.path)
880 guard state.isEditable else { return .failure(.message("\(name) isn't UTF-8, so it can't be changed.")) }
881 guard let (edit, start, level) = insert(into: state) else { return .failure(.message("Can't find \(parent.label) any more.")) }
882 try state.apply([edit], baseRevision: state.revision)
883 if case .conflict = try saver.save(&state, to: url) { return .failure(.message("\(name) changed on disk; nothing was added.")) }
884 return .success(target(start, level, FileRecord.hash(state.mergeBase)))
885 } catch {
886 return .failure(.message("Can't add \(title): \(error.localizedDescription)"))
887 }
888 }
889
890 public enum RefileFailure: Error, Equatable {
891 case message(String)
892 }
893
894 /// The edit `org-refile-new-child` makes in `text` under the heading at `start` (nil for
895 /// the file), and where the new heading starts and its level.
896 static func newChild(_ text: String, under start: Int??, title: String) -> (edit: TextEdit, start: Int, level: Int) {
897 let ns = text as NSString
898 var prefix = ""
899 var pos = ns.length
900 var level = 1
901 if case .some(.some(let heading)) = start {
902 var stars = 0
903 while heading + stars < ns.length, ns.character(at: heading + stars) == 42 { stars += 1 }
904 level = stars + 1
905 // `org-end-of-subtree t t`: the next heading at this level or above.
906 var at = NSMaxRange(ns.lineRange(for: NSRange(location: heading, length: 0)))
907 pos = ns.length
908 while at < ns.length {
909 let line = ns.lineRange(for: NSRange(location: at, length: 0))
910 var n = 0
911 while at + n < NSMaxRange(line), ns.character(at: at + n) == 42 { n += 1 }
912 if n > 0, n <= stars, at + n < ns.length, [32, 9].contains(ns.character(at: at + n)) {
913 pos = at
914 break
915 }
916 at = NSMaxRange(line)
917 }
918 } else if ns.length > 0, ns.character(at: ns.length - 1) != 10 {
919 prefix = "\n"
920 }
921 // `org-back-over-empty-lines`.
922 var back = pos
923 while back > 0, [32, 9, 10, 13].contains(ns.character(at: back - 1)) { back -= 1 }
924 var lineAfter = back
925 while lineAfter < ns.length, ns.character(at: lineAfter) != 10 { lineAfter += 1 }
926 if lineAfter < ns.length { lineAfter += 1 }
927 if !prefix.isEmpty { lineAfter = ns.length }
928 let at = min(lineAfter, pos)
929 let insertion = prefix + "\n" + String(repeating: "*", count: level) + " " + title + "\n"
930 let newStart = at + (prefix as NSString).length + 1
931 return (TextEdit(range: at..<at, replacement: insertion), newStart, level)
932 }
933
934 /// The file `archive(from:now:)` moves the entry to, or nil when it can't tell.
935 public func archiveFile(from: (path: String, offset: Int)? = nil, now: Date = Date()) -> String? {
936 guard let (path, context) = source(from, now: now), case .success(let destination) = Archive.destination(context, sourcePath: path) else { return nil }
937 return destination.path
938 }
939
940 /// Archives the subtree at the caret, or at `from`, where `org-archive-subtree` would.
941 /// Returns a message.
942 @discardableResult
943 public func archive(from: (path: String, offset: Int)? = nil, now: Date = Date()) -> String? {
944 guard let (path, context) = source(from, now: now) else { return from == nil ? nil : "Can't read the entry's file." }
945 let destination: Archive.Destination
946 switch Archive.destination(context, sourcePath: path) {
947 case .success(let value): destination = value
948 case .failure(.message(let message)): return message
949 }
950 // An archive file open in a buffer takes the subtree there.
951 if !destination.isSameFile, let open = entry(destination.path) {
952 let state = open.buffer.document
953 let name = (destination.path as NSString).lastPathComponent
954 guard state.isEditable else { return "\(name) isn't UTF-8, so it can't be changed." }
955 let edits: Archive.Edits
956 switch Archive.run(context, sourcePath: path, destination: destination, archiveText: state.text) {
957 case .success(let value): edits = value
958 case .failure(.message(let message)): return message
959 }
960 if let archiveEdit = edits.archive {
961 let edit = EditResult(baseRevision: state.revision, edits: [archiveEdit])
962 if case .failed(let message) = open.buffer.perform(PrecomputedEdit(edit), now: now, answers: [:]) { return message }
963 changed(open)
964 }
965 if let message = applySource(edits.source, path: path, now: now) { return message }
966 return "Archived to \(name)"
967 }
968 do {
969 let url = URL(fileURLWithPath: destination.path)
970 let existing = destination.isSameFile ? nil : try fileSystem.read(url)
971 var state = loaded(existing ?? [], path: url.path)
972 if !destination.isSameFile, !state.isEditable { return "\(url.lastPathComponent) isn't UTF-8, so it can't be changed." }
973 let edits: Archive.Edits
974 switch Archive.run(context, sourcePath: path, destination: destination, archiveText: existing.map { _ in state.text }) {
975 case .success(let value): edits = value
976 case .failure(.message(let message)): return message
977 }
978 if let archiveEdit = edits.archive {
979 try state.apply([archiveEdit], baseRevision: state.revision)
980 if case .conflict = try saver.save(&state, to: url) { return "\(url.lastPathComponent) changed on disk; nothing was archived." }
981 }
982 if let message = applySource(edits.source, path: path, now: now) { return message }
983 return destination.isSameFile ? "Archived under \(destination.heading ?? "the end of the file")" : "Archived to \(url.lastPathComponent)"
984 } catch {
985 return "Can't archive: \(error.localizedDescription)"
986 }
987 }
988
989 // MARK: - Commands from other views
990
991 /// Where the heading line `line` is now in `path`: at `offset` if it still reads so, else
992 /// the copy of the line nearest `offset`. For acting on agenda entries after other edits
993 /// moved them.
994 public func locateHeading(path: String, line: String, near offset: Int) -> Int? {
995 guard let text = entry(path)?.buffer.document.text ?? (try? fileSystem.read(URL(fileURLWithPath: path))).flatMap({ $0.map { SourceText(bytes: $0).text } }) else { return nil }
996 let ns = text as NSString
997 let length = (line as NSString).length
998 if offset + length <= ns.length, ns.substring(with: NSRange(location: offset, length: length)) == line,
999 offset == 0 || ns.character(at: offset - 1) == 10 {
1000 return offset
1001 }
1002 var best: Int?
1003 var search = NSRange(location: 0, length: ns.length)
1004 while true {
1005 let found = ns.range(of: line, options: [], range: search)
1006 guard found.location != NSNotFound else { break }
1007 let atLineStart = found.location == 0 || ns.character(at: found.location - 1) == 10
1008 let lineEnd = NSMaxRange(found) == ns.length || ns.character(at: NSMaxRange(found)) == 10
1009 if atLineStart, lineEnd, best.map({ abs($0 - offset) > abs(found.location - offset) }) ?? true { best = found.location }
1010 search = NSRange(location: NSMaxRange(found), length: ns.length - NSMaxRange(found))
1011 }
1012 return best
1013 }
1014
1015 /// Runs `command` with the caret at `offset` in the file at `path`, as the agenda does:
1016 /// through the buffer when the file is open, leaving its caret alone; otherwise on the
1017 /// file, written back at once through the save path. `expect` is the heading line the
1018 /// caller saw at a position; if the text there changed, nothing runs.
1019 public func perform(
1020 _ command: any OrgCommand, path: String, at offset: Int, expect: (start: Int, line: String)?,
1021 answers: [String: String] = [:], now: Date = Date()
1022 ) -> CommandStep {
1023 let stale = CommandStep.failed("The entry changed; the agenda has been refreshed.")
1024 func matches(_ text: String) -> Bool {
1025 guard let expect else { return true }
1026 let ns = text as NSString
1027 guard expect.start + (expect.line as NSString).length <= ns.length else { return false }
1028 return ns.substring(with: NSRange(location: expect.start, length: (expect.line as NSString).length)) == expect.line
1029 }
1030 if let entry = entry(path) {
1031 let buffer = entry.buffer
1032 guard matches(buffer.document.text) else { return stale }
1033 do {
1034 let options = self.options
1035 let step = try buffer.update { try $0.run(command, selection: [offset..<offset], now: now, answers: answers, options: options) }
1036 if case .commit = step { changed(entry) }
1037 return step
1038 } catch {
1039 return .failed("\(error)")
1040 }
1041 }
1042 let url = URL(fileURLWithPath: path)
1043 let name = url.lastPathComponent
1044 do {
1045 guard let bytes = try fileSystem.read(url) else { return .failed("\(name) no longer exists.") }
1046 var state = loaded(bytes, path: path)
1047 guard state.isEditable else { return .failed("\(name) isn't UTF-8, so it can't be changed.") }
1048 guard matches(state.text) else { return stale }
1049 let step = try state.run(command, selection: [offset..<offset], now: now, answers: answers, options: options)
1050 if case .commit = step, state.isDirty, case .conflict = try saver.save(&state, to: url) {
1051 return .failed("\(name) changed on disk; nothing was changed.")
1052 }
1053 if case .commit = step { textChanged?(path) }
1054 return step
1055 } catch {
1056 return .failed("Can't change \(name): \(error.localizedDescription)")
1057 }
1058 }
1059
1060 /// Applies `edits`, computed against `expected`, to `path` as one change, as Replace in
1061 /// Files and the renames do. An open buffer takes them as an edit its editor can undo; a
1062 /// buffer with no editor yet, and a file that isn't open, first has its text kept in
1063 /// recovery (labelled `replace`), and the file is written through the save path. Nil when
1064 /// done, else why not; nothing changes when the text is no longer `expected`.
1065 public func applyChanges(_ edits: [TextEdit], to path: String, expecting expected: String, now: Date = Date()) -> String? {
1066 let url = URL(fileURLWithPath: path)
1067 let name = url.lastPathComponent
1068 let stale = "\(name) changed after the search; nothing was changed in it."
1069 if let entry = entry(path) {
1070 let state = entry.buffer.document
1071 guard state.isEditable else { return "\(name) isn't UTF-8, so it can't be changed." }
1072 guard state.text == expected else { return stale }
1073 if entry.buffer is StateBuffer {
1074 do { try recovery.keep(try state.encodedText(), for: url, label: "replace") } catch {
1075 return "Can't keep a copy of \(name): \(error.localizedDescription)"
1076 }
1077 }
1078 if case .failed(let message) = entry.buffer.perform(PrecomputedEdit(EditResult(baseRevision: state.revision, edits: edits)), now: now, answers: [:]) {
1079 return message
1080 }
1081 changed(entry)
1082 return nil
1083 }
1084 do {
1085 guard let bytes = try fileSystem.read(url) else { return "\(name) no longer exists." }
1086 var state = loaded(bytes, path: path)
1087 guard state.isEditable else { return "\(name) isn't UTF-8, so it can't be changed." }
1088 guard state.text == expected else { return stale }
1089 try recovery.keep(bytes, for: url, label: "replace")
1090 try state.apply(edits, baseRevision: state.revision)
1091 if case .conflict = try saver.save(&state, to: url) { return "\(name) changed on disk; nothing was changed." }
1092 textChanged?(path)
1093 return nil
1094 } catch {
1095 return "Can't change \(name): \(error.localizedDescription)"
1096 }
1097 }
1098
1099 // MARK: - External work
1100
1101 /// Recalculates a table in Emacs from a snapshot of the buffer, then replaces the table
1102 /// with Emacs's text if it hasn't changed meanwhile. Returns a message for the echo area.
1103 public func recalculateInEmacs(table: Range<Int>, point: Int, form: String) async -> String {
1104 guard let programs = Self.runner else {
1105 #if os(macOS)
1106 return "Tables that need Emacs aren't recalculated in this version of orgstar."
1107 #else
1108 return "Tables that need Emacs aren't recalculated on iOS."
1109 #endif
1110 }
1111 guard let entry = current else { return "No file is open." }
1112 let path = entry.path
1113 let snapshot = entry.buffer.document.text as NSString
1114 guard table.upperBound <= snapshot.length else { return "The table moved; try again." }
1115 let old = snapshot.substring(with: NSRange(table))
1116 let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
1117 do {
1118 let new = try await programs.recalculateTable(text: snapshot as String, directory: directory, table: table, point: point, form: form)
1119 guard entries.contains(where: { $0 === entry }) else { return "The file was closed before Emacs finished." }
1120 let current = entry.buffer
1121 let text = current.document.text as NSString
1122 guard table.upperBound <= text.length, text.substring(with: NSRange(table)) == old else {
1123 return "The table changed while Emacs recalculated it; nothing was changed."
1124 }
1125 guard new != old else { return "Recalculated in Emacs" }
1126 let result = EditResult(baseRevision: current.document.revision, edits: [TextEdit(range: table, replacement: new)])
1127 if case .failed(let message) = current.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
1128 changed(entry)
1129 return "Recalculated in Emacs"
1130 } catch is CancellationError {
1131 return "Recalculation canceled"
1132 } catch {
1133 return "\(error)"
1134 }
1135 }
1136
1137 /// Runs a src block and writes its result under it, unless the block changed while it
1138 /// ran. Returns a message for the echo area.
1139 public func runBabel(_ job: BabelJob) async -> String {
1140 guard let entry = current else { return "No file is open." }
1141 let directory = URL(fileURLWithPath: entry.path).deletingLastPathComponent()
1142 let programs = Self.runner
1143 /// A program through `programs`; without it, Emacs Lisp in `Elisp` and js in
1144 /// JavaScriptCore, and nothing else.
1145 func run(_ job: BabelJob) async throws -> BabelOutput {
1146 if let output = job.known { return output }
1147 if let programs { return try await programs.runBabel(job, fileDirectory: directory) }
1148 #if canImport(JavaScriptCore)
1149 if let output = try await JavaScriptBlocks.run(job, directory: directory) { return output }
1150 #endif
1151 if job.calc != nil { return try TableReason.calcBlock(job) }
1152 #if canImport(SQLite3)
1153 if let output = try SQLiteBlocks.run(job, directory: directory) { return output }
1154 #endif
1155 #if canImport(WebKit)
1156 if let output = try await DiagramBlocks.run(job, directory: directory) { return output }
1157 #endif
1158 guard let output = try Babel.evaluateNatively(job) else {
1159 #if os(macOS)
1160 throw Babel.Failure.message(job.lispForm == nil
1161 ? "\(job.language) blocks don't run in this version of orgstar."
1162 : "This block uses Emacs Lisp that runs only in Emacs.")
1163 #else
1164 throw Babel.Failure.message(job.lispForm == nil
1165 ? "\(job.language) blocks need the Mac to run."
1166 : "This block uses Emacs Lisp that runs only in Emacs, on the Mac.")
1167 #endif
1168 }
1169 return output
1170 }
1171 /// Writes the result to `:file`, when the block asks for that; a message when it can't.
1172 func write(_ job: BabelJob, _ output: BabelOutput) -> String? {
1173 guard let file = Babel.fileResult(job, output: output) else { return nil }
1174 do {
1175 try file.contents.write(to: Self.resultFile(file.path, job: job, directory: directory), atomically: true, encoding: .utf8)
1176 return nil
1177 } catch {
1178 return "Can't write \(file.path): \(error.localizedDescription)"
1179 }
1180 }
1181 // Without programs, a block that refers to one that can't run here runs nothing.
1182 if programs == nil, !job.needs.isEmpty, let language = ([job.language] + job.referenced).first(where: { !Self.inProcess.contains($0) }) {
1183 #if os(macOS)
1184 return "This block needs a \(language) block, and \(language) blocks don't run in this version of orgstar; nothing was run."
1185 #else
1186 return "This block needs a \(language) block, and \(language) blocks need the Mac to run; nothing was run."
1187 #endif
1188 }
1189 do {
1190 // Blocks the `:var`s, `:post` and noweb references refer to run first, one at a time.
1191 // Each is one of the blocks agreed to, or the run stops: the text may have changed
1192 // while a block ran.
1193 var job = job
1194 let approved = job.approved
1195 func agreed(_ block: BabelJob) -> Bool { approved.isEmpty || approved.contains(block.blockText) }
1196 if job.needsFile {
1197 let document = entry.buffer.document
1198 switch Babel.replan(job, file: entry.path, text: document.text, tree: document.tree) {
1199 case .failure(.message(let message)): return message
1200 case .success(let next): job = next
1201 }
1202 }
1203 while let need = job.needs.first {
1204 guard agreed(need.job) else { return "The blocks changed while running; nothing more was run." }
1205 let output = try await run(need.job)
1206 guard entries.contains(where: { $0 === entry }) else { return "The file was closed before the block finished." }
1207 if let message = write(need.job, output) { return message }
1208 let document = entry.buffer.document
1209 switch Babel.resume(job, need: need, output: output, text: document.text, tree: document.tree) {
1210 case .failure(.message(let message)): return message
1211 case .success(let next): job = next
1212 }
1213 }
1214 guard agreed(job) else { return "The blocks changed while running; nothing more was run." }
1215 let output = try await run(job)
1216 guard entries.contains(where: { $0 === entry }) else { return "The file was closed before the block finished." }
1217 if let message = write(job, output) { return message }
1218 let current = entry.buffer
1219 let document = current.document
1220 let done = output.problem ?? "Code block evaluation complete."
1221 switch Babel.finish(job, output: output, text: document.text, settings: document.tree.settings) {
1222 case .failure(.message(let message)):
1223 return message
1224 case .success(let edits):
1225 guard !edits.isEmpty else { return job.finish.params.contains("silent") ? output.problem ?? output.stdout : done }
1226 let result = EditResult(baseRevision: document.revision, edits: edits)
1227 if case .failed(let message) = current.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
1228 changed(entry)
1229 return done
1230 }
1231 } catch is CancellationError {
1232 return "Code block canceled."
1233 } catch Babel.Failure.message(let message) {
1234 return message
1235 } catch {
1236 return "\(error)"
1237 }
1238 }
1239
1240 /// The languages that run without programs.
1241 static let inProcess: Set<String> = ["emacs-lisp", "elisp", "js", "javascript", "calc", "sqlite", "dot", "mermaid"]
1242
1243 /// Where a block's `:file` result goes: relative to `:dir`, itself relative to `directory`.
1244 static func resultFile(_ name: String, job: BabelJob, directory: URL) -> URL {
1245 let runDirectory = job.directory.map { URL(fileURLWithPath: $0, relativeTo: directory).standardizedFileURL } ?? directory
1246 return name.hasPrefix("/") ? URL(fileURLWithPath: name) : runDirectory.appendingPathComponent(name)
1247 }
1248
1249 /// The `:file` the block writes its result to, for the open file; nil without one.
1250 public func resultFile(of job: BabelJob) -> String? {
1251 guard let path, let name = job.finish.file else { return nil }
1252 return Self.resultFile(name, job: job, directory: URL(fileURLWithPath: path).deletingLastPathComponent()).path
1253 }
1254
1255 /// The block running now, to cancel.
1256 @ObservationIgnored private var babelTask: Task<String, Never>?
1257 public private(set) var isRunningBabel = false
1258
1259 /// Runs a src block in the background; its message comes back through `report`.
1260 public func startBabel(_ job: BabelJob, report: @escaping @MainActor (String) -> Void) {
1261 babelTask?.cancel()
1262 isRunningBabel = true
1263 let task = Task { await runBabel(job) }
1264 babelTask = task
1265 Task {
1266 let message = await task.value
1267 if babelTask == task {
1268 babelTask = nil
1269 isRunningBabel = false
1270 }
1271 report(message)
1272 }
1273 }
1274
1275 /// Stops the running block; its results aren't inserted.
1276 public func cancelBabel() {
1277 babelTask?.cancel()
1278 }
1279
1280 // MARK: - Locations
1281
1282 /// Opens the file of `location` if needed and asks the editor to show the heading. Offsets
1283 /// are used only if the buffer matches what was indexed; otherwise the heading is found
1284 /// again by position and title.
1285 public func show(_ location: HeadingLocation) {
1286 if path != location.path { open(location.path) }
1287 guard let document else { return }
1288 let hash = FileRecord.hash(document.mergeBase)
1289 let offset: Int
1290 if !isDirty, hash == location.contentHash {
1291 offset = location.start
1292 } else if location.ordinal == HeadingLocation.fileOrdinal {
1293 offset = 0
1294 } else if location.ordinal < outline.count, outline[location.ordinal].title == location.title {
1295 offset = outline[location.ordinal].start
1296 } else if let entry = outline.first(where: { $0.title == location.title }) {
1297 offset = entry.start
1298 } else {
1299 return
1300 }
1301 reveal(offset)
1302 }
1303
1304 /// Asks the focused pane's editor to show `offset`.
1305 public func reveal(_ offset: Int) {
1306 reveal(offset, in: focused)
1307 }
1308
1309 /// Asks `pane`'s editor to show `offset`.
1310 public func reveal(_ offset: Int, in pane: EditorPane) {
1311 requestID += 1
1312 pane.revealRequest = (offset, requestID)
1313 }
1314
1315 /// Called when the workspace sees a file change on disk: an open buffer of it takes the
1316 /// change in.
1317 public func fileChanged(_ path: String) {
1318 let interval = Perf.begin("session.fileChanged")
1319 defer { interval.end((path as NSString).lastPathComponent) }
1320 guard let entry = entry(path) else { return }
1321 let name = (path as NSString).lastPathComponent
1322 let read: [UInt8]?
1323 do {
1324 read = try fileSystem.read(URL(fileURLWithPath: path))
1325 } catch {
1326 showError(String(localized: "Couldn't Read File", comment: "Error alert title"), "Can't read \(name): \(error.localizedDescription)")
1327 return
1328 }
1329 guard let bytes = read else { return }
1330 let buffer = entry.buffer
1331 guard bytes != buffer.document.mergeBase else { return }
1332 switch buffer.update({ $0.diskChanged(to: bytes) }) {
1333 case .conflict:
1334 entry.autosave?.cancel()
1335 entry.conflict = "\(name) changed on disk, and the changes conflict with yours."
1336 case .merged, .reloaded:
1337 entry.conflict = nil
1338 resolveSetup(entry)
1339 // Edits merged with the disk's still need saving.
1340 scheduleAutosave(entry)
1341 case .unchanged:
1342 break
1343 }
1344 refresh(entry)
1345 }
1346}
1347
1348/// `base`, telling `written` about each file it replaced.
1349private struct WriteReporting: FileSystem {
1350 let base: FileSystem
1351 let written: @Sendable (URL) -> Void
1352
1353 func read(_ url: URL) throws -> [UInt8]? { try base.read(url) }
1354
1355 func replace(_ url: URL, with bytes: [UInt8]) throws -> [UInt8]? {
1356 let replaced = try base.replace(url, with: bytes)
1357 written(url)
1358 return replaced
1359 }
1360}