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