Sources/OrgApp/DocumentSession.swift
1678 lines · 86582 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 }
167
168 // MARK: - Encryption
169
170 /// `org-crypt-use-before-save-magic`: entries with `cryptTag` are encrypted on every save.
171 public var encryptsTaggedEntries: Bool {
172 get { crypt.encryptsTaggedEntries }
173 set { crypt.encryptsTaggedEntries = newValue }
174 }
175
176 /// `org-crypt-tag-matcher`.
177 public var cryptTag: String {
178 get { crypt.tag }
179 set { crypt.tag = newValue }
180 }
181
182 /// Open files that aren't saved until a passphrase is given: tagged entries that would be
183 /// written unencrypted, or an encrypted file without one. Other edits to them wait too.
184 public private(set) var held: [String: CryptHold] = [:]
185 /// Holds from saves that failed: a version on disk with tagged entries that can't be kept
186 /// encrypted, or an entry the passphrase can't encrypt. Kept until a save succeeds.
187 @ObservationIgnored private var failedHolds: [String: CryptHold] = [:]
188
189 /// An encrypted file waiting for its passphrase to open, and the pane to show it in.
190 public private(set) var unlockRequest: String?
191 @ObservationIgnored private var unlockPane: EditorPane?
192
193 /// Passphrases saved in the Keychain, used after Touch ID, Face ID or the device's password
194 /// while the setting is on.
195 @ObservationIgnored public var passphrases = CryptPassphrases.shared
196 /// Files whose remembered passphrase is being asked for, and those where it was refused:
197 /// the Keychain is asked once per file until the file closes or Encrypt is chosen.
198 @ObservationIgnored private var askingKeychain: Set<String> = []
199 @ObservationIgnored private var refusedKeychain: Set<String> = []
200
201 public static func isEncryptedFile(_ path: String) -> Bool { CryptVault.isEncryptedFile(path) }
202
203 /// An encrypted org file, which lists with the org files.
204 public static func isEncryptedOrgFile(_ path: String) -> Bool { path.hasSuffix(".org.gpg") }
205
206 /// Gives `passphrase` for `path`: an encrypted file opens with it, and a held file is saved.
207 /// It must open the file, or the file's encrypted entries if it has any. A message when it
208 /// doesn't.
209 public func unlock(_ passphrase: String, for path: String) -> String? {
210 if let entry = entry(path) {
211 if let message = OrgCrypt.firstMessage(entry.buffer.document.text), !OrgCrypt.opens(message, passphrase: passphrase) {
212 return String(localized: "Wrong passphrase")
213 }
214 // An encrypted file on disk keeps its passphrase: a passphrase given after Forget
215 // must open it.
216 if Self.isEncryptedFile(entry.path), let disk = try? diskFileSystem.read(URL(fileURLWithPath: entry.path)),
217 !CryptVault.opens(disk, passphrase: passphrase) {
218 return String(localized: "Wrong passphrase")
219 }
220 crypt.unlock(passphrase, for: entry.path)
221 refusedKeychain.remove(entry.path)
222 save(entry)
223 return nil
224 }
225 guard Self.isEncryptedFile(path) else { return nil }
226 let bytes: [UInt8]
227 do {
228 guard let read = try diskFileSystem.read(URL(fileURLWithPath: path)) else { return "\((path as NSString).lastPathComponent) no longer exists." }
229 bytes = read
230 } catch {
231 return error.localizedDescription
232 }
233 guard CryptVault.opens(bytes, passphrase: passphrase) else { return String(localized: "Wrong passphrase") }
234 crypt.unlock(passphrase, for: path)
235 let pane = unlockPane.flatMap { pane in panes.contains { $0 === pane } ? pane : nil } ?? focused
236 unlockRequest = nil
237 unlockPane = nil
238 open(path, in: pane)
239 return nil
240 }
241
242 /// The encrypted file waiting for its passphrase stays closed.
243 public func cancelUnlock() {
244 if let unlockRequest { passphrases.endSession(for: unlockRequest) }
245 unlockRequest = nil
246 unlockPane = nil
247 }
248
249 /// A crypt command used `passphrase` for `path`: saves use it from now on, without asking.
250 public func cryptUsed(_ passphrase: String, for path: String) {
251 crypt.unlock(passphrase, for: path)
252 refusedKeychain.remove(path)
253 }
254
255 /// The entry holding `plaintext` in `path`'s buffer was decrypted from `message`.
256 public func cryptDecrypted(message: String, plaintext: String, for path: String) {
257 crypt.remember(message: message, plaintext: plaintext, for: path)
258 }
259
260 /// Forget Encryption Passphrase: the passphrase leaves the Keychain and the session.
261 public func forgetPassphrase(for path: String) {
262 passphrases.forget(path)
263 crypt.forgetPassphrase(for: path)
264 }
265
266 /// `title`, of the heading at `heading` in `path`, as it may be shown and kept outside
267 /// the editor (the clock's file, widgets, the Live Activity, the menu bar): a placeholder
268 /// for a heading of an encrypted file or one inside an entry that's encrypted on disk.
269 public func shareableTitle(_ title: String, path: String, heading: Int) -> String {
270 let hidden = Self.isEncryptedFile(path)
271 || (crypt.sealsEntries(for: path) && document(of: path).map { OrgCrypt.isInTaggedText($0.text, at: heading, tag: cryptTag) } == true)
272 return hidden ? String(localized: "Encrypted entry") : title
273 }
274
275 /// Why a copy of the buffer can't be kept, with what to do; the buffer's notice shows.
276 private func keepFailure(_ hold: CryptHold) -> String {
277 if let current { _ = updateHold(current) }
278 return hold.localizedDescription + ". " + String(localized: "Give the passphrase with Encrypt… first, so that a copy of your edits can be kept encrypted.")
279 }
280
281 /// Whether `path`'s buffer is held back from disk now.
282 private func updateHold(_ entry: Entry) -> CryptHold? {
283 let dirty = entry.buffer.document.isDirty
284 let hold = dirty ? crypt.hold(entry.buffer.document.text, for: entry.path) ?? failedHolds[entry.path] : nil
285 if held[entry.path] != hold { held[entry.path] = hold }
286 return hold
287 }
288
289 /// Asks the Keychain for `entry`'s passphrase, once, and saves with it.
290 private func askKeychain(_ entry: Entry) {
291 let path = entry.path
292 guard !askingKeychain.contains(path), !refusedKeychain.contains(path), passphrases.hasStored(path) else { return }
293 askingKeychain.insert(path)
294 Task { [weak self, weak entry] in
295 guard let self else { return }
296 let passphrase = await self.passphrases.stored(for: path)
297 self.askingKeychain.remove(path)
298 guard let entry, self.entries.contains(where: { $0 === entry }) else { return }
299 if let passphrase, self.unlock(passphrase, for: path) == nil { return }
300 self.refusedKeychain.insert(path)
301 }
302 }
303
304 // MARK: - Panes
305
306 /// A new, empty pane.
307 public func makePane() -> EditorPane {
308 let pane = EditorPane()
309 panes.append(pane)
310 return pane
311 }
312
313 /// Removes `pane`; its buffers stay open. The last pane stays.
314 public func closePane(_ pane: EditorPane) {
315 guard panes.count > 1, let index = panes.firstIndex(where: { $0 === pane }) else { return }
316 panes.remove(at: index)
317 if focused === pane { focused = panes[0] }
318 }
319
320 /// The panes showing `path`.
321 private func panes(showing path: String) -> [EditorPane] {
322 panes.filter { $0.path == path }
323 }
324
325 private var buffer: DocumentBuffer? { current?.buffer }
326 /// The focused buffer's pending autosave, for tests to wait on.
327 var autosave: Task<Void, Never>? { current?.autosave }
328 private var url: URL? { path.map { URL(fileURLWithPath: $0) } }
329 /// Whether the open file is an org file (`.org`, `.org_archive`), not plain text.
330 public var isOrg: Bool { path.map(Self.isOrgPath) ?? false }
331
332 public static func isOrgPath(_ path: String) -> Bool {
333 path.hasSuffix(".org") || path.hasSuffix(".org_archive") || path.hasSuffix(".org.gpg")
334 }
335
336 /// Whether the open file is Markdown, which has highlighting, heading folds and an outline.
337 public var isMarkdown: Bool { path.map(Markdown.isPath) ?? false }
338
339 /// The outline of `path`'s text: org headings, or Markdown's; none for other files.
340 static func outline(_ path: String, _ state: DocumentState) -> [OutlineEntry] {
341 if isOrgPath(path) { return Presentation.outline(state.tree) }
342 return Markdown.isPath(path) ? MarkdownDocument(state.text).outline : []
343 }
344
345 /// The caret in the open file.
346 public var caret: Int { buffer?.selection.first?.lowerBound ?? 0 }
347 private var name: String { path.map { ($0 as NSString).lastPathComponent } ?? "" }
348
349 /// The open buffer of `path`, or of the same file by another path (`find-buffer-visiting`
350 /// by truename).
351 private func entry(_ path: String) -> Entry? {
352 if let exact = entries.first(where: { $0.path == path }) { return exact }
353 let truename = URL(fileURLWithPath: path).resolvingSymlinksInPath().path
354 return entries.first { URL(fileURLWithPath: $0.path).resolvingSymlinksInPath().path == truename }
355 }
356
357 /// The text of `path`: its buffer's when it's open, else what's on disk.
358 public func text(of path: String) -> String? {
359 if let entry = entry(path) { return entry.buffer.document.text }
360 guard let bytes = try? fileSystem.read(URL(fileURLWithPath: path)) else { return nil }
361 let state = loaded(bytes, path: path)
362 return state.isEditable ? state.text : nil
363 }
364
365 /// A copy of `path`'s text and tree, its buffer's when it's open, for changes made apart
366 /// and written back with `ReplaceChangedText`.
367 public func copy(of path: String) -> DocumentState? {
368 if let entry = entry(path) { return entry.buffer.document }
369 guard let bytes = try? fileSystem.read(URL(fileURLWithPath: path)) else { return nil }
370 let state = loaded(bytes, path: path)
371 return state.isEditable ? state : nil
372 }
373
374 /// The buffer's name as uniquify writes it (`post-forward-angle-brackets`): the file name,
375 /// with as many of its folders as tell it apart from other open files of the same name.
376 public func bufferName(_ path: String) -> String {
377 let name = (path as NSString).lastPathComponent
378 let others = openPaths.filter { $0 != path && ($0 as NSString).lastPathComponent == name }
379 guard !others.isEmpty else { return name }
380 func folders(_ p: String) -> [String] { (p as NSString).deletingLastPathComponent.split(separator: "/").map(String.init).reversed() }
381 let mine = folders(path)
382 var count = 1
383 while count < mine.count, others.contains(where: { folders($0).prefix(count) == mine.prefix(count) }) { count += 1 }
384 return name + "<" + mine.prefix(count).reversed().joined(separator: "/") + ">"
385 }
386
387 public func isOpen(_ path: String) -> Bool { entry(path) != nil }
388
389 /// The document of an open file, whichever pane shows it.
390 public func document(of path: String) -> DocumentState? { entry(path)?.buffer.document }
391
392 /// Whether `buffer` is the live state of `path`, as `attach` made it.
393 public func isAttached(_ buffer: DocumentBuffer, for path: String) -> Bool { entry(path)?.buffer === buffer }
394
395 /// The caret of an open file.
396 public func caret(of path: String) -> Int? { entry(path)?.buffer.selection.first?.lowerBound }
397
398 /// The text of every open file, for views that read files (the agenda, search).
399 public var openDocuments: [(path: String, document: DocumentState)] {
400 entries.map { ($0.path, $0.buffer.document) }
401 }
402
403 /// The text of every open file by path, for the agenda and what it writes (widgets, the
404 /// watch, reminders). Encrypted files, and files with entries decrypted that saving
405 /// encrypts, are left out: those views read them from disk.
406 public var openTexts: [String: String] {
407 let shown = entries.filter { !crypt.isPrivate($0.buffer.document.text, for: $0.path) }
408 return Dictionary(shown.map { ($0.path, $0.buffer.document.text) }, uniquingKeysWith: { a, _ in a })
409 }
410
411 /// The text of `path` for an export that writes files (iCalendar, publishing): an open
412 /// buffer's, unless it holds what's encrypted on disk, then what's on disk; nil for an
413 /// encrypted file.
414 public func exportText(of path: String) -> String? {
415 if Self.isEncryptedFile(path) { return nil }
416 if let entry = entry(path), !crypt.isPrivate(entry.buffer.document.text, for: entry.path) { return entry.buffer.document.text }
417 return (try? diskFileSystem.read(URL(fileURLWithPath: path))).flatMap { $0 }.flatMap { String(bytes: $0, encoding: .utf8) }
418 }
419
420 /// Whether `exportText` leaves `path` out or reads it from disk for what's encrypted.
421 public func exportLeavesOut(_ path: String) -> Bool {
422 Self.isEncryptedFile(path) || entry(path).map { crypt.isPrivate($0.buffer.document.text, for: $0.path) } == true
423 }
424
425 /// Why the buffer of `path` isn't copied to a temporary file for Emacs (recalculating,
426 /// exporting, `elisp:` links): it's an encrypted file, or holds entries encrypted on disk.
427 public func refusesEmacsCopy(_ path: String) -> String? {
428 let name = (path as NSString).lastPathComponent
429 if Self.isEncryptedFile(path) { return String(localized: "\(name) is encrypted, so Emacs isn't given a copy of it.") }
430 guard let entry = entry(path), crypt.isPrivate(entry.buffer.document.text, for: entry.path) else { return nil }
431 return String(localized: "\(name) has decrypted entries that are encrypted on disk, so Emacs isn't given a copy of it.")
432 }
433
434 /// Said after an export that left out encrypted files or read decrypted entries from disk.
435 public static var exportNote: String {
436 String(localized: "Encrypted files were left out, and encrypted entries were exported as they are on disk.")
437 }
438
439 /// Open buffers, most recently shown first.
440 public var recentPaths: [String] { history.filter(isOpen) }
441
442 /// Shows the buffer of `path` in the focused pane, opening the file if it isn't open.
443 public func open(_ path: String) {
444 open(path, in: focused)
445 }
446
447 /// Shows the buffer of `path` in `pane`, opening the file if it isn't open.
448 public func open(_ path: String, in pane: EditorPane) {
449 let interval = Perf.begin("session.open")
450 defer { interval.end((path as NSString).lastPathComponent) }
451 if let existing = entry(path) {
452 show(existing, in: pane)
453 return
454 }
455 if Self.isEncryptedFile(path), crypt.passphrase(for: path) == nil,
456 (try? diskFileSystem.read(URL(fileURLWithPath: path)))??.isEmpty == false {
457 unlockRequest = path
458 unlockPane = pane
459 return
460 }
461 do {
462 guard let bytes = try fileSystem.read(URL(fileURLWithPath: path)) else {
463 showError(String(localized: "Couldn't Open File", comment: "Error alert title"), "\((path as NSString).lastPathComponent) no longer exists.")
464 return
465 }
466 let entry = Entry(path: path, buffer: StateBuffer(loaded(bytes, path: path)))
467 crypt.opened(path)
468 let index = pane.path.flatMap(self.entry).flatMap { c in entries.firstIndex { $0 === c } }.map { $0 + 1 } ?? entries.count
469 entries.insert(entry, at: index)
470 show(entry, in: pane)
471 } catch {
472 showError(String(localized: "Couldn't Open File", comment: "Error alert title"), "Can't open \(path): \(error.localizedDescription)")
473 }
474 }
475
476 private func show(_ entry: Entry, in pane: EditorPane) {
477 pane.path = entry.path
478 if !pane.shown.contains(entry.path) { pane.shown.append(entry.path) }
479 pane.history.removeAll { $0 == entry.path }
480 pane.history.insert(entry.path, at: 0)
481 pane.revealRequest = nil
482 history.removeAll { $0 == entry.path }
483 history.insert(entry.path, at: 0)
484 refresh(pane)
485 // A worker ready ahead of the first user command run in this buffer.
486 #if canImport(WebKit)
487 if !userCommands.all.isEmpty { userCommandHost()?.prepare() }
488 #endif
489 }
490
491 /// The buffer before or after the focused one, wrapping, in the focused pane.
492 public func cycle(_ step: Int) {
493 guard let current, let index = entries.firstIndex(where: { $0 === current }), entries.count > 1 else { return }
494 show(entries[((index + step) % entries.count + entries.count) % entries.count], in: focused)
495 }
496
497 /// The buffer shown before the focused one.
498 public func showPrevious() {
499 guard let previous = recentPaths.dropFirst().first else { return }
500 open(previous)
501 }
502
503 /// Closes the buffer of `path` without saving it. A pane showing it shows the buffer it
504 /// showed before, else the most recent other buffer, else nothing.
505 public func kill(_ path: String) {
506 guard let entry = entry(path) else { return }
507 entry.autosave?.cancel()
508 entries.removeAll { $0 === entry }
509 crypt.close(entry.path)
510 passphrases.endSession(for: entry.path)
511 held[entry.path] = nil
512 failedHolds[entry.path] = nil
513 refusedKeychain.remove(entry.path)
514 history.removeAll { $0 == path }
515 outlineUpdates[path]?.cancel()
516 outlineUpdates[path] = nil
517 for pane in panes {
518 pane.shown.removeAll { $0 == path }
519 pane.history.removeAll { $0 == path }
520 guard pane.path == path else { continue }
521 if let next = pane.history.first.flatMap(self.entry) ?? recentPaths.first.flatMap(self.entry) ?? entries.last {
522 show(next, in: pane)
523 } else {
524 pane.path = nil
525 pane.outline = []
526 pane.isDirty = false
527 pane.isReadOnly = false
528 pane.conflict = nil
529 pane.revealRequest = nil
530 }
531 }
532 refreshLists()
533 }
534
535 /// Closes the focused buffer without saving, as when its file was deleted.
536 public func close() {
537 if let path { kill(path) }
538 }
539
540 /// Makes `buffer`, built from `document`, the live state of the focused file.
541 public func attach(_ buffer: DocumentBuffer) {
542 if let path { attach(buffer, for: path) }
543 }
544
545 /// Makes `buffer`, built from the file's `document`, the live state of `path`.
546 public func attach(_ buffer: DocumentBuffer, for path: String) {
547 guard let entry = entry(path) else { return }
548 entry.buffer = buffer
549 for pane in panes(showing: path) { refresh(pane) }
550 }
551
552 /// The buffer of `path` changed in its editor: the panes showing it update their views
553 /// once typing pauses, and it saves on its own.
554 public func bufferChanged(_ path: String) {
555 guard let entry = entry(path) else { return }
556 changed(entry)
557 }
558
559 /// The focused buffer changed through typing.
560 public func bufferChanged() {
561 if let current { changed(current) }
562 }
563
564 /// A buffer changed, typed or not: the panes showing it update their views, the outline
565 /// once typing pauses, and it saves on its own.
566 private func changed(_ entry: Entry) {
567 let showing = panes(showing: entry.path)
568 for pane in showing { refresh(pane, outline: false) }
569 outlineUpdates[entry.path]?.cancel()
570 if !showing.isEmpty {
571 let path = entry.path
572 outlineUpdates[path] = Task { [weak self, weak entry] in
573 try? await Task.sleep(for: .milliseconds(300))
574 guard !Task.isCancelled, let self, let entry else { return }
575 let outline = Self.outline(path, entry.buffer.document)
576 for pane in self.panes(showing: path) {
577 pane.outline = outline
578 pane.editVersion += 1
579 }
580 }
581 }
582 scheduleAutosave(entry)
583 refreshLists()
584 textChanged?(entry.path)
585 }
586
587 /// `pane`'s view of its buffer, from the buffer's state.
588 private func refresh(_ pane: EditorPane, outline updateOutline: Bool = true) {
589 let interval = Perf.begin("session.refresh")
590 defer { interval.end() }
591 refreshLists()
592 guard let entry = pane.path.flatMap(entry) else { return }
593 let state = entry.buffer.document
594 if pane.isDirty != state.isDirty { pane.isDirty = state.isDirty }
595 if pane.isReadOnly == state.isEditable { pane.isReadOnly = !state.isEditable }
596 if pane.conflict != entry.conflict { pane.conflict = entry.conflict }
597 if updateOutline {
598 pane.outline = Self.outline(entry.path, state)
599 pane.editVersion += 1
600 }
601 }
602
603 /// Every pane showing `entry`, from the buffer's state.
604 private func refresh(_ entry: Entry) {
605 for pane in panes(showing: entry.path) { refresh(pane) }
606 }
607
608 /// The focused pane, from its buffer's state.
609 private func refresh() {
610 refresh(focused)
611 }
612
613 private func refreshLists() {
614 let paths = entries.map(\.path)
615 if paths != openPaths { openPaths = paths }
616 let dirty = Set(entries.filter { $0.buffer.document.isDirty }.map(\.path))
617 if dirty != dirtyPaths { dirtyPaths = dirty }
618 }
619
620 // MARK: - Saving
621
622 private var saver: Saver {
623 Saver(fileSystem: WriteReporting(base: fileSystem) { [weak self] url in MainActor.assumeIsolated { self?.fileWritten?(url.path) } }, recovery: recovery)
624 }
625
626 /// The saver for a file that isn't open, whose state is thrown away after the save: a
627 /// version another writer put on disk just before ours, which recovery can't keep, is put
628 /// back as it was, and the change fails. A version written after ours is left in place.
629 private var closedFileSaver: Saver {
630 var saver = saver
631 let crypt = crypt, disk = diskFileSystem
632 saver.restoreOverwritten = { url in
633 guard let last = crypt.takeReplaced(for: url.path), try disk.read(url) == last.written else { return }
634 _ = try disk.replace(url, with: last.replaced)
635 }
636 return saver
637 }
638
639 private func scheduleAutosave(_ entry: Entry) {
640 entry.autosave?.cancel()
641 // A held file whose edits were undone, or whose tagged entries went, isn't held.
642 if held[entry.path] != nil, updateHold(entry) == nil { refresh(entry) }
643 guard saveMode == .automatic, entry.buffer.document.isDirty, entry.conflict == nil else { return }
644 entry.autosave = Task { [weak self, weak entry, autosaveDelay] in
645 try? await Task.sleep(for: autosaveDelay)
646 guard !Task.isCancelled, let self, let entry else { return }
647 self.save(entry)
648 }
649 }
650
651 /// Saves the current buffer now. True when nothing is left unsaved.
652 @discardableResult
653 public func save() -> Bool {
654 guard let current else { return true }
655 return save(current)
656 }
657
658 /// Saves the buffer of `path`. True when nothing is left unsaved.
659 @discardableResult
660 public func save(_ path: String) -> Bool {
661 guard let entry = entry(path) else { return true }
662 return save(entry)
663 }
664
665 /// Saves every open buffer. True when nothing is left unsaved.
666 @discardableResult
667 public func saveAll() -> Bool {
668 entries.map { save($0) }.allSatisfy { $0 }
669 }
670
671 @discardableResult
672 private func save(_ entry: Entry) -> Bool {
673 let interval = Perf.begin("session.save")
674 defer { interval.end((entry.path as NSString).lastPathComponent) }
675 entry.autosave?.cancel()
676 let name = (entry.path as NSString).lastPathComponent
677 // A failed save is tried again: what failed may be fixed by now.
678 guard updateHold(entry) == nil || held[entry.path] == failedHolds[entry.path] else {
679 askKeychain(entry)
680 refresh(entry)
681 return false
682 }
683 guard entry.buffer.document.isDirty else { return true }
684 guard entry.conflict == nil else { return false }
685 defer { _ = updateHold(entry) }
686 do {
687 let outcome = try entry.buffer.update { try saver.save(&$0, to: URL(fileURLWithPath: entry.path)) }
688 failedHolds[entry.path] = nil
689 switch outcome {
690 case .saved, .mergedAndSaved:
691 break
692 case .conflict:
693 entry.conflict = "\(name) changed on disk, and the changes conflict with yours."
694 case .overwroteExternalChange(let change), .changedAfterWrite(let change):
695 if case .conflict(let conflicts) = change {
696 // No conflicts listed: both versions went into the buffer between markers.
697 entry.conflict = conflicts.isEmpty
698 ? String(localized: "\(name) changed on disk while saving, and the changes conflict with yours; both are in the editor between conflict markers.")
699 : "\(name) changed on disk while saving, and the changes conflict with yours."
700 }
701 }
702 } catch let hold as CryptHold {
703 // A version on disk with tagged entries in plaintext can be kept only encrypted.
704 failedHolds[entry.path] = hold
705 askKeychain(entry)
706 } catch let failure as OrgCrypt.Failure {
707 failedHolds[entry.path] = .blocked(failure.description)
708 } catch {
709 showError(String(localized: "Couldn't Save File", comment: "Error alert title"), "Can't save \(name): \(error.localizedDescription)")
710 }
711 refresh(entry)
712 return !entry.buffer.document.isDirty
713 }
714
715 /// Resolves a conflict by writing the buffer over the disk version, which goes to recovery.
716 public func keepMine() {
717 guard let buffer, let url else { return }
718 if let current, updateHold(current) != nil { return refresh() }
719 do {
720 try buffer.update { try saver.overwrite(&$0, to: url) }
721 current?.conflict = nil
722 } catch let hold as CryptHold {
723 // The version on disk can be kept only encrypted: the passphrase first.
724 if let current {
725 failedHolds[current.path] = hold
726 _ = updateHold(current)
727 askKeychain(current)
728 }
729 } catch {
730 showError(String(localized: "Couldn't Save File", comment: "Error alert title"), "Can't save \(name): \(error.localizedDescription)")
731 }
732 refresh()
733 }
734
735 /// Resolves a conflict by loading the disk version; the buffer goes to recovery.
736 public func useDiskVersion() {
737 guard let buffer, let url else { return }
738 do {
739 guard let bytes = try fileSystem.read(url) else { return }
740 if isDirty { try recovery.keep(try buffer.document.encodedText(), for: url, label: "local") }
741 let path = url.path
742 buffer.update { $0 = loaded(bytes, path: path) }
743 current?.conflict = nil
744 } catch let hold as CryptHold {
745 showError(String(localized: "Couldn't Keep a Copy", comment: "Error alert title"), keepFailure(hold))
746 } catch {
747 showError(String(localized: "Couldn't Read File", comment: "Error alert title"), "Can't read \(name): \(error.localizedDescription)")
748 }
749 refresh()
750 }
751
752 // MARK: - Comparing versions
753
754 /// The buffer, the file on disk and the version both started from, while they conflict.
755 public func conflictVersions() -> (mine: String, disk: String, base: String)? {
756 guard current?.conflict != nil, let buffer, let url, let disk = try? fileSystem.read(url) else { return nil }
757 return (buffer.document.text, SourceText(bytes: disk).text, SourceText(bytes: buffer.document.mergeBase).text)
758 }
759
760 /// Resolves a conflict as `git merge` leaves one: the buffer holds both sides' changes, those
761 /// that conflict between markers, to fix and save. The disk version becomes the base, and
762 /// the buffer as it was goes to recovery.
763 public func mergeConflictWithMarkers() {
764 guard let versions = conflictVersions(), let buffer, let url, let disk = try? fileSystem.read(url) else { return }
765 do {
766 try recovery.keep(try buffer.document.encodedText(), for: url, label: "local")
767 let merged = mergeWithMarkers(base: versions.base, ours: versions.mine, theirs: versions.disk, oursLabel: "yours", theirsLabel: "disk")
768 try buffer.update { state in
769 state = loaded(disk, path: url.path)
770 try state.apply(lineEdits(from: versions.disk, to: merged), baseRevision: state.revision)
771 }
772 current?.conflict = nil
773 } catch let hold as CryptHold {
774 showError(String(localized: "Couldn't Keep a Copy", comment: "Error alert title"), keepFailure(hold))
775 } catch {
776 showError(String(localized: "Couldn't Merge", comment: "Error alert title"), "Can't merge \(name): \(error.localizedDescription)")
777 }
778 refresh()
779 }
780
781 /// Syncthing's conflict copies of the open file beside it: `name.sync-conflict-DATE-TIME-ID.ext`.
782 public func syncConflictCopies() -> [URL] {
783 guard let url else { return [] }
784 let folder = url.deletingLastPathComponent()
785 let stem = NSRegularExpression.escapedPattern(for: url.deletingPathExtension().lastPathComponent)
786 let ext = url.pathExtension.isEmpty ? "" : "\\." + NSRegularExpression.escapedPattern(for: url.pathExtension)
787 let pattern = "^" + stem + "\\.sync-conflict-[0-9]{8}-[0-9]{6}-[A-Z0-9]+" + ext + "$"
788 let names = (try? FileManager.default.contentsOfDirectory(atPath: folder.path)) ?? []
789 return names.filter { $0.range(of: pattern, options: .regularExpression) != nil }.sorted().map { folder.appendingPathComponent($0) }
790 }
791
792 /// What to do with a conflict copy: keep the file as it is, take the copy's text, or merge
793 /// the two with markers. The copy goes to recovery and is removed.
794 public enum CopyResolution { case keepFile, useCopy, merge }
795
796 public func resolve(copy: URL, _ resolution: CopyResolution) -> String? {
797 guard let buffer, let url else { return "No file is open" }
798 do {
799 guard let bytes = try diskFileSystem.read(copy).map({ try crypt.plain($0, for: url.path) }) else { return "\(copy.lastPathComponent) is gone" }
800 let copyText = SourceText(bytes: bytes).text
801 let mine = buffer.document.text
802 let new: String? = switch resolution {
803 case .keepFile: nil
804 case .useCopy: copyText
805 case .merge: mergeWithMarkers(base: nil, ours: mine, theirs: copyText, oursLabel: url.lastPathComponent, theirsLabel: copy.lastPathComponent)
806 }
807 if let new, new != mine {
808 let result = EditResult(baseRevision: buffer.document.revision, edits: lineEdits(from: mine, to: new))
809 if case .failed(let message) = buffer.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
810 }
811 try recovery.keep(bytes, for: url, label: "sync-conflict")
812 try FileManager.default.removeItem(at: copy)
813 } catch {
814 return "Can't resolve \(copy.lastPathComponent): \(error.localizedDescription)"
815 }
816 if let current { changed(current) }
817 return nil
818 }
819
820 /// Versions of the open file kept in recovery, newest first, with when and why each was
821 /// kept.
822 public func recoveryVersions() -> [(url: URL, date: Date, label: String)] {
823 guard let url, let store = diskRecovery as? FileRecoveryStore, let versions = try? store.versions(for: url) else { return [] }
824 // `STAMP-LABEL-UUID8-NAME`, as `FileRecoveryStore.keep` names them.
825 return versions.reversed().map { version in
826 let m = version.lastPathComponent.firstMatch(of: /^([0-9]+)-(.+?)-([0-9A-Fa-f]{8})-/)
827 let nanos = m.flatMap { UInt64($0.1) } ?? 0
828 return (version, Date(timeIntervalSince1970: Double(nanos) / 1_000_000_000), m.map { String($0.2) } ?? "")
829 }
830 }
831
832 /// The text of a kept version.
833 public func recoveryText(_ version: URL) -> String? {
834 guard let bytes = (try? diskFileSystem.read(version)).flatMap({ $0 }) else { return nil }
835 // Kept as the open file is: encrypted with its passphrase, its entries' messages known.
836 return (try? path.map { try crypt.plain(bytes, for: $0) } ?? bytes).map { SourceText(bytes: $0).text }
837 }
838
839 /// Puts a kept version's text in the buffer, as an edit that can be undone; the buffer as it
840 /// was goes to recovery.
841 public func restore(_ version: URL) -> String? {
842 guard let text = recoveryText(version) else { return "Can't read that version" }
843 return restore(text: text)
844 }
845
846 /// Puts `text`, an earlier version of the file, in the buffer as an edit that can be undone;
847 /// the buffer as it was goes to recovery.
848 public func restore(text: String) -> String? {
849 guard let buffer, let url else { return "Can't read that version" }
850 do {
851 try recovery.keep(try buffer.document.encodedText(), for: url, label: "local")
852 } catch let hold as CryptHold {
853 return keepFailure(hold)
854 } catch {
855 return "Can't keep the current version: \(error.localizedDescription)"
856 }
857 let mine = buffer.document.text
858 let result = EditResult(baseRevision: buffer.document.revision, edits: lineEdits(from: mine, to: text))
859 if case .failed(let message) = buffer.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
860 if let current { changed(current) }
861 return nil
862 }
863
864 // MARK: - Moving subtrees
865
866 /// The current context of the buffer, as commands see it.
867 private func editContext(now: Date) -> EditContext? {
868 guard let buffer else { return nil }
869 let document = buffer.document
870 return EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: buffer.selection, now: now, options: options)
871 }
872
873 /// The file and context a subtree command works on: `from` (a file and a heading in it,
874 /// as the agenda gives them), or the current buffer at its caret.
875 private func source(_ from: (path: String, offset: Int)?, now: Date) -> (path: String, context: EditContext)? {
876 guard let from else {
877 guard let path, let context = editContext(now: now) else { return nil }
878 return (path, context)
879 }
880 let state: DocumentState
881 if let open = entry(from.path) {
882 state = open.buffer.document
883 } else {
884 guard let bytes = try? fileSystem.read(URL(fileURLWithPath: from.path)) else { return nil }
885 state = loaded(bytes, path: from.path)
886 }
887 guard state.isEditable else { return nil }
888 let context = EditContext(revision: state.revision, text: state.text, tree: state.tree, selection: [from.offset..<from.offset], now: now, options: options)
889 return (from.path, context)
890 }
891
892 /// Applies an edit computed from `source(_:now:)` to that file, open or not.
893 private func applySource(_ edit: EditResult, path: String, now: Date) -> String? {
894 if case .failed(let message) = perform(PrecomputedEdit(edit), path: path, at: 0, expect: nil, now: now) { return message }
895 return nil
896 }
897
898 /// Moves the subtree at the caret, or at `from`, under `target`, or with `keep` copies it
899 /// there (`org-copy`). For another file, that file is written first, through the save
900 /// path; the subtree leaves its file only once it has. Returns a message for the echo area.
901 @discardableResult
902 public func refile(to target: RefileTarget, from: (path: String, offset: Int)? = nil, keep: Bool = false, now: Date = Date()) -> String? {
903 guard case (let path, var context)? = source(from, now: now) else { return from == nil ? nil : "Can't read the entry's file." }
904 do {
905 switch prepareMove(path, context: context, to: target.path) {
906 case .refused(let message): return message
907 case .sealed(let heading):
908 guard let again = source((path, heading), now: now) else { return "Can't read the entry's file." }
909 context = again.context
910 case .ready: break
911 }
912 }
913 let done = (keep ? "Copied to " : "Refiled to ") + target.label
914 if target.path == path {
915 let answers = ["refile": target.start.map(String.init) ?? ""]
916 let command = RefileWithinFile(keep: keep)
917 let step = from == nil ? buffer?.perform(command, now: now, answers: answers)
918 : perform(command, path: path, at: from!.offset, expect: nil, answers: answers, now: now)
919 if case .failed(let message)? = step { return message }
920 if from == nil { bufferChanged() }
921 return done
922 }
923 let url = URL(fileURLWithPath: target.path)
924 let targetName = (target.path as NSString).lastPathComponent
925 // A target open in a buffer takes the subtree there, with its unsaved edits.
926 if let open = entry(target.path) {
927 let state = open.buffer.document
928 guard state.isEditable else { return "\(targetName) isn't UTF-8, so it can't be changed." }
929 guard let start = target.locate(in: state) else { return "Can't find \(target.label) any more." }
930 guard let result = Refile.toOtherFile(source: context, target: state.text, under: start, keep: keep) else { return "Can't refile from here." }
931 let edit = EditResult(baseRevision: state.revision, edits: [result.target])
932 if case .failed(let message) = open.buffer.perform(PrecomputedEdit(edit), now: now, answers: [:]) { return message }
933 changed(open)
934 if !keep, let message = applySource(result.source, path: path, now: now) { return message }
935 return done
936 }
937 do {
938 guard let bytes = try fileSystem.read(url) else { return "\(targetName) no longer exists." }
939 var state = loaded(bytes, path: url.path)
940 guard state.isEditable else { return "\(targetName) isn't UTF-8, so it can't be changed." }
941 guard let start = target.locate(in: state) else { return "Can't find \(target.label) any more." }
942 guard let result = Refile.toOtherFile(source: context, target: state.text, under: start, keep: keep) else { return "Can't refile from here." }
943 try state.apply([result.target], baseRevision: state.revision)
944 if case .conflict = try closedFileSaver.save(&state, to: url) { return "\(targetName) changed on disk; nothing was refiled." }
945 if !keep, let message = applySource(result.source, path: path, now: now) { return message }
946 return done
947 } catch {
948 return "Can't refile: \(error.localizedDescription)"
949 }
950 }
951
952 /// `org-refile-new-child`: a heading `title` at the end of `parent`'s subtree, one level
953 /// below it, or at the end of the file for a file target. Returns the new heading as a
954 /// target, or a message.
955 public func createRefileChild(under parent: RefileTarget, title: String, now: Date = Date()) -> Result<RefileTarget, RefileFailure> {
956 let name = (parent.path as NSString).lastPathComponent
957 func insert(into state: DocumentState) -> (edit: TextEdit, start: Int, level: Int)? {
958 guard let start = parent.locate(in: state) else { return nil }
959 return Self.newChild(state.text, under: start, title: title)
960 }
961 func target(_ start: Int, _ level: Int, _ hash: String) -> RefileTarget {
962 RefileTarget(label: parent.label + "/" + title, path: parent.path, start: start, title: title, level: level, contentHash: hash)
963 }
964 if let open = entry(parent.path) {
965 let state = open.buffer.document
966 guard state.isEditable else { return .failure(.message("\(name) isn't UTF-8, so it can't be changed.")) }
967 guard let (edit, start, level) = insert(into: state) else { return .failure(.message("Can't find \(parent.label) any more.")) }
968 if case .failed(let message) = open.buffer.perform(PrecomputedEdit(EditResult(baseRevision: state.revision, edits: [edit])), now: now, answers: [:]) {
969 return .failure(.message(message))
970 }
971 changed(open)
972 return .success(target(start, level, ""))
973 }
974 do {
975 let url = URL(fileURLWithPath: parent.path)
976 guard let bytes = try fileSystem.read(url) else { return .failure(.message("\(name) no longer exists.")) }
977 var state = loaded(bytes, path: url.path)
978 guard state.isEditable else { return .failure(.message("\(name) isn't UTF-8, so it can't be changed.")) }
979 guard let (edit, start, level) = insert(into: state) else { return .failure(.message("Can't find \(parent.label) any more.")) }
980 try state.apply([edit], baseRevision: state.revision)
981 if case .conflict = try closedFileSaver.save(&state, to: url) { return .failure(.message("\(name) changed on disk; nothing was added.")) }
982 return .success(target(start, level, FileRecord.hash(state.mergeBase)))
983 } catch {
984 return .failure(.message("Can't add \(title): \(error.localizedDescription)"))
985 }
986 }
987
988 public enum RefileFailure: Error, Equatable {
989 case message(String)
990 }
991
992 /// The edit `org-refile-new-child` makes in `text` under the heading at `start` (nil for
993 /// the file), and where the new heading starts and its level.
994 static func newChild(_ text: String, under start: Int??, title: String) -> (edit: TextEdit, start: Int, level: Int) {
995 let ns = text as NSString
996 var prefix = ""
997 var pos = ns.length
998 var level = 1
999 if case .some(.some(let heading)) = start {
1000 var stars = 0
1001 while heading + stars < ns.length, ns.character(at: heading + stars) == 42 { stars += 1 }
1002 level = stars + 1
1003 // `org-end-of-subtree t t`: the next heading at this level or above.
1004 var at = NSMaxRange(ns.lineRange(for: NSRange(location: heading, length: 0)))
1005 pos = ns.length
1006 while at < ns.length {
1007 let line = ns.lineRange(for: NSRange(location: at, length: 0))
1008 var n = 0
1009 while at + n < NSMaxRange(line), ns.character(at: at + n) == 42 { n += 1 }
1010 if n > 0, n <= stars, at + n < ns.length, [32, 9].contains(ns.character(at: at + n)) {
1011 pos = at
1012 break
1013 }
1014 at = NSMaxRange(line)
1015 }
1016 } else if ns.length > 0, ns.character(at: ns.length - 1) != 10 {
1017 prefix = "\n"
1018 }
1019 // `org-back-over-empty-lines`.
1020 var back = pos
1021 while back > 0, [32, 9, 10, 13].contains(ns.character(at: back - 1)) { back -= 1 }
1022 var lineAfter = back
1023 while lineAfter < ns.length, ns.character(at: lineAfter) != 10 { lineAfter += 1 }
1024 if lineAfter < ns.length { lineAfter += 1 }
1025 if !prefix.isEmpty { lineAfter = ns.length }
1026 let at = min(lineAfter, pos)
1027 let insertion = prefix + "\n" + String(repeating: "*", count: level) + " " + title + "\n"
1028 let newStart = at + (prefix as NSString).length + 1
1029 return (TextEdit(range: at..<at, replacement: insertion), newStart, level)
1030 }
1031
1032 private enum MovePreparation {
1033 case ready
1034 /// Tagged entries in the subtree were encrypted in its file; its heading starts here.
1035 case sealed(Int)
1036 case refused(String)
1037 }
1038
1039 /// Before the subtree at the caret of `context`, in `path`, moves to the file `target`: an
1040 /// encrypted file's entries go only to another encrypted file, which takes the same
1041 /// passphrase; tagged entries with text in the subtree are encrypted where they are first,
1042 /// since the tag they inherit doesn't go with them.
1043 private func prepareMove(_ path: String, context: EditContext, to target: String) -> MovePreparation {
1044 // Within the file, an entry keeps its own tag; one inside an encrypted entry would leave it.
1045 if target == path {
1046 guard crypt.sealsEntries(for: path), let heading = OrgCrypt.heading(context.text, at: context.selection.first?.lowerBound ?? 0),
1047 OrgCrypt.isInTaggedText(context.text, at: heading, tag: cryptTag) else { return .ready }
1048 return .refused(String(localized: "This heading is inside an encrypted entry, so it isn't moved on its own; move the encrypted entry."))
1049 }
1050 // The target's passphrase, lent by the source for the move, isn't kept after it.
1051 if Self.isEncryptedFile(target), !isOpen(target) {
1052 DispatchQueue.main.async { [weak self] in
1053 guard let self, !self.isOpen(target) else { return }
1054 self.crypt.close(target)
1055 }
1056 }
1057 let from = (path as NSString).lastPathComponent, to = (target as NSString).lastPathComponent
1058 if Self.isEncryptedFile(path) {
1059 guard Self.isEncryptedFile(target) else {
1060 return .refused(String(localized: "\(from) is encrypted, and \(to) isn't; the entry wasn't moved."))
1061 }
1062 if crypt.passphrase(for: target) == nil, let passphrase = crypt.passphrase(for: path) {
1063 let disk = (try? diskFileSystem.read(URL(fileURLWithPath: target))).flatMap { $0 } ?? []
1064 guard CryptVault.opens(disk, passphrase: passphrase) else {
1065 return .refused(String(localized: "\(to) has another passphrase; open it first."))
1066 }
1067 crypt.unlock(passphrase, for: target)
1068 }
1069 }
1070 guard crypt.sealsEntries(for: path), let heading = OrgCrypt.heading(context.text, at: context.selection.first?.lowerBound ?? 0) else { return .ready }
1071 // A heading inside an encrypted entry is in that entry's message on disk; moved on its
1072 // own, its title would be in plaintext.
1073 if OrgCrypt.isInTaggedText(context.text, at: heading, tag: cryptTag) {
1074 return .refused(String(localized: "This heading is inside an encrypted entry, so it isn't moved on its own; move the encrypted entry."))
1075 }
1076 let end = OrgCrypt.bodyRange(context.text, at: heading)?.upperBound ?? heading
1077 let subtree = heading..<max(heading + 1, end)
1078 guard !OrgCrypt.unencrypted(context.text, tag: cryptTag, within: subtree).isEmpty else { return .ready }
1079 guard let passphrase = crypt.passphrase(for: path) else {
1080 return .refused(String(localized: "Tagged entries in the subtree aren't encrypted; give the passphrase with Encrypt… first."))
1081 }
1082 let sealed: String
1083 do {
1084 sealed = try OrgCrypt.seal(context.text, passphrase: passphrase, tag: cryptTag, within: subtree).text
1085 } catch {
1086 return .refused("\(error)")
1087 }
1088 let edit = EditResult(baseRevision: context.revision, edits: lineEdits(from: context.text, to: sealed))
1089 if let open = entry(path) {
1090 if case .failed(let message) = open.buffer.perform(PrecomputedEdit(edit), now: Date(), answers: [:]) { return .refused(message) }
1091 changed(open)
1092 } else {
1093 do {
1094 guard let bytes = try fileSystem.read(URL(fileURLWithPath: path)) else { return .refused("\(from) no longer exists.") }
1095 var state = loaded(bytes, path: path)
1096 try state.apply(edit.edits, baseRevision: state.revision)
1097 if case .conflict = try closedFileSaver.save(&state, to: URL(fileURLWithPath: path)) { return .refused("\(from) changed on disk; nothing was moved.") }
1098 } catch {
1099 return .refused("Can't encrypt the entry: \(error.localizedDescription)")
1100 }
1101 }
1102 return .sealed(heading)
1103 }
1104
1105 /// The file `archive(from:now:)` moves the entry to, or nil when it can't tell.
1106 public func archiveFile(from: (path: String, offset: Int)? = nil, now: Date = Date()) -> String? {
1107 guard let (path, context) = source(from, now: now), case .success(let destination) = Archive.destination(context, sourcePath: path) else { return nil }
1108 return destination.path
1109 }
1110
1111 /// Archives the subtree at the caret, or at `from`, where `org-archive-subtree` would.
1112 /// Returns a message.
1113 @discardableResult
1114 public func archive(from: (path: String, offset: Int)? = nil, now: Date = Date()) -> String? {
1115 guard case (let path, var context)? = source(from, now: now) else { return from == nil ? nil : "Can't read the entry's file." }
1116 let destination: Archive.Destination
1117 switch Archive.destination(context, sourcePath: path) {
1118 case .success(let value): destination = value
1119 case .failure(.message(let message)): return message
1120 }
1121 do {
1122 switch prepareMove(path, context: context, to: destination.isSameFile ? path : destination.path) {
1123 case .refused(let message): return message
1124 case .sealed(let heading):
1125 guard let again = source((path, heading), now: now) else { return "Can't read the entry's file." }
1126 context = again.context
1127 case .ready: break
1128 }
1129 }
1130 // An archive file open in a buffer takes the subtree there.
1131 if !destination.isSameFile, let open = entry(destination.path) {
1132 let state = open.buffer.document
1133 let name = (destination.path as NSString).lastPathComponent
1134 guard state.isEditable else { return "\(name) isn't UTF-8, so it can't be changed." }
1135 let edits: Archive.Edits
1136 switch Archive.run(context, sourcePath: path, destination: destination, archiveText: state.text) {
1137 case .success(let value): edits = value
1138 case .failure(.message(let message)): return message
1139 }
1140 if let archiveEdit = edits.archive {
1141 let edit = EditResult(baseRevision: state.revision, edits: [archiveEdit])
1142 if case .failed(let message) = open.buffer.perform(PrecomputedEdit(edit), now: now, answers: [:]) { return message }
1143 changed(open)
1144 }
1145 if let message = applySource(edits.source, path: path, now: now) { return message }
1146 return "Archived to \(name)"
1147 }
1148 do {
1149 let url = URL(fileURLWithPath: destination.path)
1150 let existing = destination.isSameFile ? nil : try fileSystem.read(url)
1151 var state = loaded(existing ?? [], path: url.path)
1152 if !destination.isSameFile, !state.isEditable { return "\(url.lastPathComponent) isn't UTF-8, so it can't be changed." }
1153 let edits: Archive.Edits
1154 switch Archive.run(context, sourcePath: path, destination: destination, archiveText: existing.map { _ in state.text }) {
1155 case .success(let value): edits = value
1156 case .failure(.message(let message)): return message
1157 }
1158 if let archiveEdit = edits.archive {
1159 try state.apply([archiveEdit], baseRevision: state.revision)
1160 if case .conflict = try closedFileSaver.save(&state, to: url) { return "\(url.lastPathComponent) changed on disk; nothing was archived." }
1161 }
1162 if let message = applySource(edits.source, path: path, now: now) { return message }
1163 return destination.isSameFile ? "Archived under \(destination.heading ?? "the end of the file")" : "Archived to \(url.lastPathComponent)"
1164 } catch {
1165 return "Can't archive: \(error.localizedDescription)"
1166 }
1167 }
1168
1169 // MARK: - Commands from other views
1170
1171 /// Where the heading line `line` is now in `path`: at `offset` if it still reads so, else
1172 /// the copy of the line nearest `offset`. For acting on agenda entries after other edits
1173 /// moved them.
1174 public func locateHeading(path: String, line: String, near offset: Int) -> Int? {
1175 guard let text = entry(path)?.buffer.document.text ?? (try? fileSystem.read(URL(fileURLWithPath: path))).flatMap({ $0.map { SourceText(bytes: $0).text } }) else { return nil }
1176 let ns = text as NSString
1177 let length = (line as NSString).length
1178 if offset + length <= ns.length, ns.substring(with: NSRange(location: offset, length: length)) == line,
1179 offset == 0 || ns.character(at: offset - 1) == 10 {
1180 return offset
1181 }
1182 var best: Int?
1183 var search = NSRange(location: 0, length: ns.length)
1184 while true {
1185 let found = ns.range(of: line, options: [], range: search)
1186 guard found.location != NSNotFound else { break }
1187 let atLineStart = found.location == 0 || ns.character(at: found.location - 1) == 10
1188 let lineEnd = NSMaxRange(found) == ns.length || ns.character(at: NSMaxRange(found)) == 10
1189 if atLineStart, lineEnd, best.map({ abs($0 - offset) > abs(found.location - offset) }) ?? true { best = found.location }
1190 search = NSRange(location: NSMaxRange(found), length: ns.length - NSMaxRange(found))
1191 }
1192 return best
1193 }
1194
1195 /// Runs `command` with the caret at `offset` in the file at `path`, as the agenda does:
1196 /// through the buffer when the file is open, leaving its caret alone; otherwise on the
1197 /// file, written back at once through the save path. `expect` is the heading line the
1198 /// caller saw at a position; if the text there changed, nothing runs.
1199 public func perform(
1200 _ command: any OrgCommand, path: String, at offset: Int, expect: (start: Int, line: String)?,
1201 answers: [String: String] = [:], now: Date = Date()
1202 ) -> CommandStep {
1203 let stale = CommandStep.failed("The entry changed; the agenda has been refreshed.")
1204 func matches(_ text: String) -> Bool {
1205 guard let expect else { return true }
1206 let ns = text as NSString
1207 guard expect.start + (expect.line as NSString).length <= ns.length else { return false }
1208 return ns.substring(with: NSRange(location: expect.start, length: (expect.line as NSString).length)) == expect.line
1209 }
1210 if let entry = entry(path) {
1211 let buffer = entry.buffer
1212 guard matches(buffer.document.text) else { return stale }
1213 do {
1214 let options = self.options
1215 let step = try buffer.update { try $0.run(command, selection: [offset..<offset], now: now, answers: answers, options: options) }
1216 if case .commit = step { changed(entry) }
1217 return step
1218 } catch {
1219 return .failed("\(error)")
1220 }
1221 }
1222 let url = URL(fileURLWithPath: path)
1223 let name = url.lastPathComponent
1224 do {
1225 guard let bytes = try fileSystem.read(url) else { return .failed("\(name) no longer exists.") }
1226 var state = loaded(bytes, path: path)
1227 guard state.isEditable else { return .failed("\(name) isn't UTF-8, so it can't be changed.") }
1228 guard matches(state.text) else { return stale }
1229 let step = try state.run(command, selection: [offset..<offset], now: now, answers: answers, options: options)
1230 if case .commit = step, state.isDirty, case .conflict = try closedFileSaver.save(&state, to: url) {
1231 return .failed("\(name) changed on disk; nothing was changed.")
1232 }
1233 if case .commit = step { textChanged?(path) }
1234 return step
1235 } catch {
1236 return .failed("Can't change \(name): \(error.localizedDescription)")
1237 }
1238 }
1239
1240 /// Applies `edits`, computed against `expected`, to `path` as one change, as Replace in
1241 /// Files and the renames do. An open buffer takes them as an edit its editor can undo; a
1242 /// buffer with no editor yet, and a file that isn't open, first has its text kept in
1243 /// recovery (labelled `replace`), and the file is written through the save path. Nil when
1244 /// done, else why not; nothing changes when the text is no longer `expected`.
1245 public func applyChanges(_ edits: [TextEdit], to path: String, expecting expected: String, now: Date = Date()) -> String? {
1246 let url = URL(fileURLWithPath: path)
1247 let name = url.lastPathComponent
1248 let stale = "\(name) changed after the search; nothing was changed in it."
1249 if let entry = entry(path) {
1250 let state = entry.buffer.document
1251 guard state.isEditable else { return "\(name) isn't UTF-8, so it can't be changed." }
1252 guard state.text == expected else { return stale }
1253 if entry.buffer is StateBuffer {
1254 // A buffer held for its passphrase keeps no copy: it can't be kept encrypted,
1255 // and the replacement can be undone in the buffer.
1256 do { try recovery.keep(try state.encodedText(), for: url, label: "replace") } catch is CryptHold {} catch {
1257 return "Can't keep a copy of \(name): \(error.localizedDescription)"
1258 }
1259 }
1260 if case .failed(let message) = entry.buffer.perform(PrecomputedEdit(EditResult(baseRevision: state.revision, edits: edits)), now: now, answers: [:]) {
1261 return message
1262 }
1263 changed(entry)
1264 return nil
1265 }
1266 do {
1267 guard let bytes = try fileSystem.read(url) else { return "\(name) no longer exists." }
1268 var state = loaded(bytes, path: path)
1269 guard state.isEditable else { return "\(name) isn't UTF-8, so it can't be changed." }
1270 guard state.text == expected else { return stale }
1271 try recovery.keep(bytes, for: url, label: "replace")
1272 try state.apply(edits, baseRevision: state.revision)
1273 if case .conflict = try closedFileSaver.save(&state, to: url) { return "\(name) changed on disk; nothing was changed." }
1274 textChanged?(path)
1275 return nil
1276 } catch {
1277 return "Can't change \(name): \(error.localizedDescription)"
1278 }
1279 }
1280
1281 // MARK: - External work
1282
1283 /// Recalculates a table in Emacs from a snapshot of the buffer, then replaces the table
1284 /// with Emacs's text if it hasn't changed meanwhile. Returns a message for the echo area.
1285 public func recalculateInEmacs(table: Range<Int>, point: Int, form: String) async -> String {
1286 guard let programs = Self.runner else {
1287 #if os(macOS)
1288 return "Tables that need Emacs aren't recalculated in this version of orgstar."
1289 #else
1290 return "Tables that need Emacs aren't recalculated on iOS."
1291 #endif
1292 }
1293 guard let entry = current else { return "No file is open." }
1294 let path = entry.path
1295 if let refusal = refusesEmacsCopy(path) { return refusal }
1296 let snapshot = entry.buffer.document.text as NSString
1297 guard table.upperBound <= snapshot.length else { return "The table moved; try again." }
1298 let old = snapshot.substring(with: NSRange(table))
1299 let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
1300 do {
1301 let new = try await programs.recalculateTable(text: snapshot as String, directory: directory, table: table, point: point, form: form)
1302 guard entries.contains(where: { $0 === entry }) else { return "The file was closed before Emacs finished." }
1303 let current = entry.buffer
1304 let text = current.document.text as NSString
1305 guard table.upperBound <= text.length, text.substring(with: NSRange(table)) == old else {
1306 return "The table changed while Emacs recalculated it; nothing was changed."
1307 }
1308 guard new != old else { return "Recalculated in Emacs" }
1309 let result = EditResult(baseRevision: current.document.revision, edits: [TextEdit(range: table, replacement: new)])
1310 if case .failed(let message) = current.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
1311 changed(entry)
1312 return "Recalculated in Emacs"
1313 } catch is CancellationError {
1314 return "Recalculation canceled"
1315 } catch {
1316 return "\(error)"
1317 }
1318 }
1319
1320 /// Runs a src block and writes its result under it, unless the block changed while it
1321 /// ran. Returns a message for the echo area.
1322 public func runBabel(_ job: BabelJob) async -> String {
1323 guard let entry = current else { return "No file is open." }
1324 let directory = URL(fileURLWithPath: entry.path).deletingLastPathComponent()
1325 let programs = Self.runner
1326 /// A program through `programs`; without it, Emacs Lisp in `Elisp`, js in
1327 /// JavaScriptCore, python in Pyodide when the app has it, and nothing else.
1328 func run(_ job: BabelJob) async throws -> BabelOutput {
1329 if let output = job.known { return output }
1330 if let programs { return try await programs.runBabel(job, fileDirectory: directory) }
1331 #if canImport(JavaScriptCore)
1332 if let output = try await JavaScriptBlocks.run(job, directory: directory) { return output }
1333 #endif
1334 #if canImport(WebKit)
1335 if let output = try await PythonBlocks.run(job, directory: directory) { return output }
1336 #endif
1337 if job.calc != nil { return try TableReason.calcBlock(job) }
1338 #if canImport(SQLite3)
1339 if let output = try SQLiteBlocks.run(job, directory: directory) { return output }
1340 #endif
1341 #if canImport(WebKit)
1342 if let output = try await DiagramBlocks.run(job, directory: directory) { return output }
1343 #endif
1344 guard let output = try Babel.evaluateNatively(job) else {
1345 #if os(macOS)
1346 throw Babel.Failure.message(job.lispForm == nil
1347 ? "\(job.language) blocks don't run in this version of orgstar."
1348 : "This block uses Emacs Lisp that runs only in Emacs.")
1349 #else
1350 throw Babel.Failure.message(job.lispForm == nil
1351 ? "\(job.language) blocks need the Mac to run."
1352 : "This block uses Emacs Lisp that runs only in Emacs, on the Mac.")
1353 #endif
1354 }
1355 return output
1356 }
1357 /// Writes the result to `:file`, when the block asks for that; a message when it can't.
1358 func write(_ job: BabelJob, _ output: BabelOutput) -> String? {
1359 guard let file = Babel.fileResult(job, output: output) else { return nil }
1360 do {
1361 try file.contents.write(to: Self.resultFile(file.path, job: job, directory: directory), atomically: true, encoding: .utf8)
1362 return nil
1363 } catch {
1364 return "Can't write \(file.path): \(error.localizedDescription)"
1365 }
1366 }
1367 // Without programs, a block that refers to one that can't run here runs nothing.
1368 if programs == nil, !job.needs.isEmpty, let language = ([job.language] + job.referenced).first(where: { !Self.inProcess.contains($0) }) {
1369 #if os(macOS)
1370 return "This block needs a \(language) block, and \(language) blocks don't run in this version of orgstar; nothing was run."
1371 #else
1372 return "This block needs a \(language) block, and \(language) blocks need the Mac to run; nothing was run."
1373 #endif
1374 }
1375 do {
1376 // Blocks the `:var`s, `:post` and noweb references refer to run first, one at a time.
1377 // Each is one of the blocks agreed to, or the run stops: the text may have changed
1378 // while a block ran.
1379 var job = job
1380 let approved = job.approved
1381 func agreed(_ block: BabelJob) -> Bool { approved.isEmpty || approved.contains(block.blockText) }
1382 if job.needsFile {
1383 let document = entry.buffer.document
1384 switch Babel.replan(job, file: entry.path, text: document.text, tree: document.tree) {
1385 case .failure(.message(let message)): return message
1386 case .success(let next): job = next
1387 }
1388 }
1389 while let need = job.needs.first {
1390 guard agreed(need.job) else { return "The blocks changed while running; nothing more was run." }
1391 let output = try await run(need.job)
1392 guard entries.contains(where: { $0 === entry }) else { return "The file was closed before the block finished." }
1393 if let message = write(need.job, output) { return message }
1394 let document = entry.buffer.document
1395 switch Babel.resume(job, need: need, output: output, text: document.text, tree: document.tree) {
1396 case .failure(.message(let message)): return message
1397 case .success(let next): job = next
1398 }
1399 }
1400 guard agreed(job) else { return "The blocks changed while running; nothing more was run." }
1401 let output = try await run(job)
1402 guard entries.contains(where: { $0 === entry }) else { return "The file was closed before the block finished." }
1403 if let message = write(job, output) { return message }
1404 let current = entry.buffer
1405 let document = current.document
1406 let done = output.problem ?? "Code block evaluation complete."
1407 switch Babel.finish(job, output: output, text: document.text, settings: document.tree.settings) {
1408 case .failure(.message(let message)):
1409 return message
1410 case .success(let edits):
1411 guard !edits.isEmpty else { return job.finish.params.contains("silent") ? output.problem ?? output.stdout : done }
1412 let result = EditResult(baseRevision: document.revision, edits: edits)
1413 if case .failed(let message) = current.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
1414 changed(entry)
1415 return done
1416 }
1417 } catch is CancellationError {
1418 return "Code block canceled."
1419 } catch Babel.Failure.message(let message) {
1420 return message
1421 } catch {
1422 return "\(error)"
1423 }
1424 }
1425
1426 /// The languages that run without programs.
1427 static var inProcess: Set<String> {
1428 var languages: Set<String> = ["emacs-lisp", "elisp", "js", "javascript", "calc", "sqlite", "dot", "mermaid"]
1429 #if canImport(WebKit)
1430 if PythonBlocks.folder != nil { languages.insert("python") }
1431 #endif
1432 return languages
1433 }
1434
1435 /// Where a block's `:file` result goes: relative to `:dir`, itself relative to `directory`.
1436 static func resultFile(_ name: String, job: BabelJob, directory: URL) -> URL {
1437 let runDirectory = job.directory.map { URL(fileURLWithPath: $0, relativeTo: directory).standardizedFileURL } ?? directory
1438 return name.hasPrefix("/") ? URL(fileURLWithPath: name) : runDirectory.appendingPathComponent(name)
1439 }
1440
1441 /// The `:file` the block writes its result to, for the open file; nil without one.
1442 public func resultFile(of job: BabelJob) -> String? {
1443 guard let path, let name = job.finish.file else { return nil }
1444 return Self.resultFile(name, job: job, directory: URL(fileURLWithPath: path).deletingLastPathComponent()).path
1445 }
1446
1447 /// The block running now, to cancel.
1448 @ObservationIgnored private var babelTask: Task<String, Never>?
1449 public private(set) var isRunningBabel = false
1450
1451 /// Runs a src block in the background; its message comes back through `report`.
1452 public func startBabel(_ job: BabelJob, report: @escaping @MainActor (String) -> Void) {
1453 babelTask?.cancel()
1454 isRunningBabel = true
1455 let task = Task { await runBabel(job) }
1456 babelTask = task
1457 Task {
1458 let message = await task.value
1459 if babelTask == task {
1460 babelTask = nil
1461 isRunningBabel = false
1462 }
1463 report(message)
1464 }
1465 }
1466
1467 /// Stops the running block; its results aren't inserted.
1468 public func cancelBabel() {
1469 babelTask?.cancel()
1470 }
1471
1472 // MARK: - User commands
1473
1474 /// The commands of `commands.toml`; their folder is where the host loads modules from.
1475 @ObservationIgnored public var userCommands = UserCommands.shared
1476 #if canImport(WebKit)
1477 @ObservationIgnored private var commandHost: CommandHost?
1478
1479 /// The host for the commands' folder, made again when the folder changed.
1480 func userCommandHost() -> CommandHost? {
1481 guard let folder = userCommands.folder else { return nil }
1482 if commandHost?.folder != folder {
1483 commandHost?.unload()
1484 commandHost = CommandHost(folder: folder)
1485 }
1486 return commandHost
1487 }
1488 #endif
1489 @ObservationIgnored private var userCommandTask: Task<String?, Never>?
1490 public private(set) var isRunningUserCommand = false
1491
1492 /// Runs a user command on the focused buffer in the background, with `context` the editor's
1493 /// context at the request's revision; the message comes back through `report`. `file` is
1494 /// the file's path relative to its folder, for `org.file()`. Prompts go to `ask`.
1495 public func startUserCommand(_ request: UserCommandRequest, context: EditContext, file: String?,
1496 ask: @escaping @MainActor (Prompt, @escaping (String?) -> Void) -> Void,
1497 report: @escaping @MainActor (String) -> Void) {
1498 userCommandTask?.cancel()
1499 isRunningUserCommand = true
1500 let task = Task { await runUserCommand(request, context: context, file: file, ask: ask, report: report) }
1501 userCommandTask = task
1502 Task {
1503 let message = await task.value
1504 if userCommandTask == task {
1505 userCommandTask = nil
1506 isRunningUserCommand = false
1507 }
1508 if let message { report(message) }
1509 }
1510 }
1511
1512 /// Stops the running user command; nothing it returns is applied.
1513 public func cancelUserCommand() {
1514 userCommandTask?.cancel()
1515 }
1516
1517 /// Why a user command doesn't run in `path`'s buffer: it's an encrypted file or holds
1518 /// decrypted entries, which a command could copy elsewhere in the file. Nil when it runs.
1519 public func refusesUserCommand(_ path: String) -> String? {
1520 let name = (path as NSString).lastPathComponent
1521 guard Self.isEncryptedFile(path) || entry(path).map({ crypt.isPrivate($0.buffer.document.text, for: $0.path) }) == true else { return nil }
1522 return String(localized: "\(name) has decrypted entries, so user commands don't run in it.", comment: "A user command refused in a buffer holding decrypted text")
1523 }
1524
1525 /// Runs `request` in the focused buffer and applies what it returns as one change at the
1526 /// request's revision. The message to show; nil when the command's own messages were shown.
1527 func runUserCommand(_ request: UserCommandRequest, context: EditContext, file: String?,
1528 ask: @escaping @MainActor (Prompt, @escaping (String?) -> Void) -> Void,
1529 report: @escaping @MainActor (String) -> Void) async -> String? {
1530 let command = request.command
1531 guard let path, let entry = entry(path) else { return "No file is open." }
1532 if let refusal = refusesUserCommand(path) { return refusal }
1533 guard entry.buffer.document.revision == request.revision, context.revision == request.revision else { return "The file changed; try again." }
1534 #if canImport(WebKit)
1535 guard let host = userCommandHost() else { return "No \(UserCommands.fileName)." }
1536 final class State {
1537 var failure: String?
1538 var quit = false
1539 }
1540 let state = State()
1541 let context = EditContext(revision: context.revision, text: context.text, tree: context.tree, selection: request.selection,
1542 now: context.now, calendar: context.calendar, options: context.options, knownTags: context.knownTags)
1543 host.calls = { name, value in
1544 if let answer = UserCommandAPI.answer(name, value, context: context, file: file) { return answer }
1545 switch name {
1546 case "prompt":
1547 let prompt = UserCommandAPI.prompt(value)
1548 return try await withCheckedThrowingContinuation { continuation in
1549 ask(prompt) { answer in
1550 guard let answer else {
1551 state.quit = true
1552 return continuation.resume(throwing: CommandHost.Failure.script("Quit"))
1553 }
1554 continuation.resume(returning: UserCommandAPI.answer(answer, to: prompt, now: Date(), calendar: context.calendar))
1555 }
1556 }
1557 case "message":
1558 report(value as? String ?? "")
1559 return NSNull()
1560 case "fail":
1561 state.failure = value as? String ?? ""
1562 return NSNull()
1563 default:
1564 throw CommandHost.Failure.script("org.\(name) isn't in API version \(UserCommands.apiVersion).")
1565 }
1566 }
1567 let json: String
1568 do {
1569 json = try await host.run(module: command.file, function: command.function, context: "null",
1570 timeout: .seconds(command.timeout), api: UserCommands.apiVersion)
1571 } catch let CommandHost.Failure.timedOut(limit) {
1572 let seconds = Int(limit.components.seconds)
1573 return String(localized: "\(command.title) didn't finish within \(seconds) s and was stopped.", comment: "A user command passed its time limit")
1574 } catch CommandHost.Failure.script(let message) {
1575 if let failure = state.failure { return failure }
1576 return state.quit ? "Quit" : "\(command.title): \(message)"
1577 } catch CommandHost.Failure.stopped {
1578 return String(localized: "\(command.title) was stopped: its web view ended, as when a command runs out of memory.", comment: "A user command whose web view ended")
1579 } catch {
1580 return String(localized: "\(command.title) canceled.", comment: "A user command canceled with Cancel Running Task")
1581 }
1582 if let failure = state.failure { return failure }
1583 guard !Task.isCancelled else { return String(localized: "\(command.title) canceled.", comment: "A user command canceled with Cancel Running Task") }
1584 switch UserCommandAPI.result(json, in: context) {
1585 case .failure(let problem):
1586 return "\(command.title): \(problem.message)"
1587 case .success(let result):
1588 guard entries.contains(where: { $0 === entry }) else { return "The file was closed before the command finished." }
1589 if case .failed(let message) = entry.buffer.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
1590 if !result.edits.isEmpty { changed(entry) }
1591 return nil
1592 }
1593 #else
1594 return "User commands aren't available here."
1595 #endif
1596 }
1597
1598 // MARK: - Locations
1599
1600 /// Opens the file of `location` if needed and asks the editor to show the heading. Offsets
1601 /// are used only if the buffer matches what was indexed; otherwise the heading is found
1602 /// again by position and title.
1603 public func show(_ location: HeadingLocation) {
1604 if path != location.path { open(location.path) }
1605 guard let document else { return }
1606 let hash = FileRecord.hash(document.mergeBase)
1607 let offset: Int
1608 if !isDirty, hash == location.contentHash {
1609 offset = location.start
1610 } else if location.ordinal == HeadingLocation.fileOrdinal {
1611 offset = 0
1612 } else if location.ordinal < outline.count, outline[location.ordinal].title == location.title {
1613 offset = outline[location.ordinal].start
1614 } else if let entry = outline.first(where: { $0.title == location.title }) {
1615 offset = entry.start
1616 } else {
1617 return
1618 }
1619 reveal(offset)
1620 }
1621
1622 /// Asks the focused pane's editor to show `offset`.
1623 public func reveal(_ offset: Int) {
1624 reveal(offset, in: focused)
1625 }
1626
1627 /// Asks `pane`'s editor to show `offset`.
1628 public func reveal(_ offset: Int, in pane: EditorPane) {
1629 requestID += 1
1630 pane.revealRequest = (offset, requestID)
1631 }
1632
1633 /// Called when the workspace sees a file change on disk: an open buffer of it takes the
1634 /// change in.
1635 public func fileChanged(_ path: String) {
1636 let interval = Perf.begin("session.fileChanged")
1637 defer { interval.end((path as NSString).lastPathComponent) }
1638 guard let entry = entry(path) else { return }
1639 let name = (path as NSString).lastPathComponent
1640 let read: [UInt8]?
1641 do {
1642 read = try fileSystem.read(URL(fileURLWithPath: path))
1643 } catch {
1644 showError(String(localized: "Couldn't Read File", comment: "Error alert title"), "Can't read \(name): \(error.localizedDescription)")
1645 return
1646 }
1647 guard let bytes = read else { return }
1648 let buffer = entry.buffer
1649 guard bytes != buffer.document.mergeBase else { return }
1650 switch buffer.update({ $0.diskChanged(to: bytes) }) {
1651 case .conflict:
1652 entry.autosave?.cancel()
1653 entry.conflict = "\(name) changed on disk, and the changes conflict with yours."
1654 case .merged, .reloaded:
1655 entry.conflict = nil
1656 resolveSetup(entry)
1657 // Edits merged with the disk's still need saving.
1658 scheduleAutosave(entry)
1659 case .unchanged:
1660 break
1661 }
1662 refresh(entry)
1663 }
1664}
1665
1666/// `base`, telling `written` about each file it replaced.
1667private struct WriteReporting: FileSystem {
1668 let base: FileSystem
1669 let written: @Sendable (URL) -> Void
1670
1671 func read(_ url: URL) throws -> [UInt8]? { try base.read(url) }
1672
1673 func replace(_ url: URL, with bytes: [UInt8]) throws -> [UInt8]? {
1674 let replaced = try base.replace(url, with: bytes)
1675 written(url)
1676 return replaced
1677 }
1678}