Sources/OrgApp/DocumentSession.swift
421 lines · 19841 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 file hasn't changed, else the
29 /// 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 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 file open in a window: its buffer, outline, saving, and requests for the editor to
46/// show a location. The view layer attaches the editor as the buffer and follows
47/// `revealRequest`.
48@MainActor
49@Observable
50public final class DocumentSession {
51 public private(set) var path: String?
52 /// A copy of the buffer's state as of its last change. Not observed: it changes on every
53 /// keystroke; views follow `path`, `isDirty` and `outline`.
54 @ObservationIgnored public private(set) var document: DocumentState?
55 public private(set) var outline: [OutlineEntry] = []
56 /// Bumped when the buffer settles after edits, and when a file opens: views that read
57 /// `document` follow this.
58 public private(set) var editVersion = 0
59 public private(set) var isDirty = false
60 /// The file isn't UTF-8, so it can't be edited or saved.
61 public private(set) var isReadOnly = false
62 /// Set while the buffer and the file on disk conflict; says how to resolve it.
63 public private(set) var conflict: String?
64 /// Bumped to ask the editor to reveal an offset.
65 public private(set) var revealRequest: (offset: Int, id: Int)?
66 public var lastError: String?
67 public var saveMode: SaveMode = .automatic
68 public var autosaveDelay: Duration = .seconds(1)
69 /// Org options for commands the session runs (refile, archive).
70 public var options: EditingOptions = .org
71 /// TODO keywords and priorities for files without their own settings.
72 public var defaults: OrgSettings = .default
73
74 private let fileSystem: FileSystem
75 private let recovery: RecoveryStore
76 @ObservationIgnored private var buffer: DocumentBuffer?
77 @ObservationIgnored var autosave: Task<Void, Never>?
78 @ObservationIgnored private var outlineUpdate: Task<Void, Never>?
79 private var requestID = 0
80
81 public init(
82 fileSystem: FileSystem = CoordinatedFileSystem(),
83 recovery: RecoveryStore = FileRecoveryStore(directory: WorkspaceModel.defaultDirectory.appendingPathComponent("Recovery"))
84 ) {
85 self.fileSystem = fileSystem
86 self.recovery = recovery
87 }
88
89 private var url: URL? { path.map { URL(fileURLWithPath: $0) } }
90 /// Whether the open file is an org file (`.org`, `.org_archive`), not plain text.
91 public var isOrg: Bool { path.map(Self.isOrgPath) ?? false }
92
93 public static func isOrgPath(_ path: String) -> Bool {
94 path.hasSuffix(".org") || path.hasSuffix(".org_archive")
95 }
96
97 /// The caret in the open file.
98 public var caret: Int { buffer?.selection.first?.lowerBound ?? 0 }
99 private var name: String { path.map { ($0 as NSString).lastPathComponent } ?? "" }
100
101 public func open(_ path: String) {
102 do {
103 guard let bytes = try fileSystem.read(URL(fileURLWithPath: path)) else {
104 lastError = "\((path as NSString).lastPathComponent) no longer exists."
105 return
106 }
107 autosave?.cancel()
108 self.path = path
109 buffer = StateBuffer(DocumentState(bytes: bytes, defaults: defaults))
110 conflict = nil
111 revealRequest = nil
112 refresh()
113 } catch {
114 lastError = "Can't open \(path): \(error.localizedDescription)"
115 }
116 }
117
118 /// Makes `buffer`, built from `document`, the live state of the open file.
119 public func attach(_ buffer: DocumentBuffer) {
120 self.buffer = buffer
121 refresh()
122 }
123
124 /// The buffer changed through typing. The outline follows once typing pauses.
125 public func bufferChanged() {
126 refresh(outline: false)
127 outlineUpdate?.cancel()
128 outlineUpdate = Task { [weak self] in
129 try? await Task.sleep(for: .milliseconds(300))
130 guard !Task.isCancelled, let self, let document = self.document else { return }
131 self.outline = self.isOrg ? Presentation.outline(document.tree) : []
132 self.editVersion += 1
133 }
134 scheduleAutosave()
135 }
136
137 private func refresh(outline updateOutline: Bool = true) {
138 guard let buffer else { return }
139 let state = buffer.document
140 document = state
141 if isDirty != state.isDirty { isDirty = state.isDirty }
142 if isReadOnly == state.isEditable { isReadOnly = !state.isEditable }
143 if updateOutline {
144 outline = isOrg ? Presentation.outline(state.tree) : []
145 editVersion += 1
146 }
147 }
148
149 // MARK: - Saving
150
151 private var saver: Saver { Saver(fileSystem: fileSystem, recovery: recovery) }
152
153 private func scheduleAutosave() {
154 autosave?.cancel()
155 guard saveMode == .automatic, isDirty, conflict == nil else { return }
156 autosave = Task { [weak self, autosaveDelay] in
157 try? await Task.sleep(for: autosaveDelay)
158 guard !Task.isCancelled else { return }
159 self?.save()
160 }
161 }
162
163 /// Saves now. True when nothing is left unsaved.
164 @discardableResult
165 public func save() -> Bool {
166 autosave?.cancel()
167 guard let buffer, let url, isDirty else { return !isDirty }
168 guard conflict == nil else { return false }
169 do {
170 let outcome = try buffer.update { try saver.save(&$0, to: url) }
171 switch outcome {
172 case .saved, .mergedAndSaved:
173 break
174 case .conflict:
175 conflict = "\(name) changed on disk, and the changes conflict with yours."
176 case .overwroteExternalChange(let change), .changedAfterWrite(let change):
177 if case .conflict = change {
178 conflict = "\(name) changed on disk while saving, and the changes conflict with yours."
179 }
180 }
181 } catch {
182 lastError = "Can't save \(name): \(error.localizedDescription)"
183 }
184 refresh()
185 return !isDirty
186 }
187
188 /// Resolves a conflict by writing the buffer over the disk version, which goes to recovery.
189 public func keepMine() {
190 guard let buffer, let url else { return }
191 do {
192 try buffer.update { try saver.overwrite(&$0, to: url) }
193 conflict = nil
194 } catch {
195 lastError = "Can't save \(name): \(error.localizedDescription)"
196 }
197 refresh()
198 }
199
200 /// Resolves a conflict by loading the disk version; the buffer goes to recovery.
201 public func useDiskVersion() {
202 guard let buffer, let url else { return }
203 do {
204 guard let bytes = try fileSystem.read(url) else { return }
205 if isDirty { try recovery.keep(try buffer.document.encodedText(), for: url, label: "local") }
206 buffer.update { $0 = DocumentState(bytes: bytes, defaults: $0.defaults) }
207 conflict = nil
208 } catch {
209 lastError = "Can't read \(name): \(error.localizedDescription)"
210 }
211 refresh()
212 }
213
214 // MARK: - Moving subtrees
215
216 /// The current context of the buffer, as commands see it.
217 private func editContext(now: Date) -> EditContext? {
218 guard let buffer else { return nil }
219 let document = buffer.document
220 return EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: buffer.selection, now: now, options: options)
221 }
222
223 /// Moves the subtree at the caret under `target`. For another file, that file is written
224 /// first, through the save path; the subtree leaves this buffer only once it has. Returns a
225 /// message for the echo area.
226 @discardableResult
227 public func refile(to target: RefileTarget, now: Date = Date()) -> String? {
228 guard let buffer, let path, let context = editContext(now: now) else { return nil }
229 if target.path == path {
230 let step = buffer.perform(RefileWithinFile(), now: now, answers: ["refile": target.start.map(String.init) ?? ""])
231 if case .failed(let message) = step { return message }
232 bufferChanged()
233 return "Refiled to \(target.label)"
234 }
235 let url = URL(fileURLWithPath: target.path)
236 do {
237 guard let bytes = try fileSystem.read(url) else { return "\((target.path as NSString).lastPathComponent) no longer exists." }
238 var state = DocumentState(bytes: bytes, defaults: defaults)
239 guard state.isEditable else { return "\((target.path as NSString).lastPathComponent) isn't UTF-8, so it can't be changed." }
240 guard let start = target.locate(in: state) else { return "Can't find \(target.label) any more." }
241 guard let result = Refile.toOtherFile(source: context, target: state.text, under: start) else { return "Can't refile from here." }
242 try state.apply([result.target], baseRevision: state.revision)
243 if case .conflict = try saver.save(&state, to: url) { return "\((target.path as NSString).lastPathComponent) changed on disk; nothing was refiled." }
244 if case .failed(let message) = buffer.perform(PrecomputedEdit(result.source), now: now, answers: [:]) { return message }
245 bufferChanged()
246 return "Refiled to \(target.label)"
247 } catch {
248 return "Can't refile: \(error.localizedDescription)"
249 }
250 }
251
252 /// Archives the subtree at the caret where `org-archive-subtree` would. Returns a message.
253 @discardableResult
254 public func archive(now: Date = Date()) -> String? {
255 guard let buffer, let path, let context = editContext(now: now) else { return nil }
256 let destination: Archive.Destination
257 switch Archive.destination(context, sourcePath: path) {
258 case .success(let value): destination = value
259 case .failure(.message(let message)): return message
260 }
261 do {
262 let url = URL(fileURLWithPath: destination.path)
263 let existing = destination.isSameFile ? nil : try fileSystem.read(url)
264 var state = DocumentState(bytes: existing ?? [], defaults: defaults)
265 if !destination.isSameFile, !state.isEditable { return "\(url.lastPathComponent) isn't UTF-8, so it can't be changed." }
266 let edits: Archive.Edits
267 switch Archive.run(context, sourcePath: path, destination: destination, archiveText: existing.map { _ in state.text }) {
268 case .success(let value): edits = value
269 case .failure(.message(let message)): return message
270 }
271 if let archiveEdit = edits.archive {
272 try state.apply([archiveEdit], baseRevision: state.revision)
273 if case .conflict = try saver.save(&state, to: url) { return "\(url.lastPathComponent) changed on disk; nothing was archived." }
274 }
275 if case .failed(let message) = buffer.perform(PrecomputedEdit(edits.source), now: now, answers: [:]) { return message }
276 bufferChanged()
277 return destination.isSameFile ? "Archived under \(destination.heading ?? "the end of the file")" : "Archived to \(url.lastPathComponent)"
278 } catch {
279 return "Can't archive: \(error.localizedDescription)"
280 }
281 }
282
283 // MARK: - Commands from other views
284
285 /// Runs `command` with the caret at `offset` in the file at `path`, as the agenda does:
286 /// through the buffer when the file is open, leaving its caret alone; otherwise on the
287 /// file, written back at once through the save path. `expect` is the heading line the
288 /// caller saw at a position; if the text there changed, nothing runs.
289 public func perform(
290 _ command: any OrgCommand, path: String, at offset: Int, expect: (start: Int, line: String)?,
291 answers: [String: String] = [:], now: Date = Date()
292 ) -> CommandStep {
293 let stale = CommandStep.failed("The entry changed; the agenda has been refreshed.")
294 func matches(_ text: String) -> Bool {
295 guard let expect else { return true }
296 let ns = text as NSString
297 guard expect.start + (expect.line as NSString).length <= ns.length else { return false }
298 return ns.substring(with: NSRange(location: expect.start, length: (expect.line as NSString).length)) == expect.line
299 }
300 if path == self.path, let buffer {
301 guard matches(buffer.document.text) else { return stale }
302 do {
303 let options = self.options
304 let step = try buffer.update { try $0.run(command, selection: [offset..<offset], now: now, answers: answers, options: options) }
305 if case .commit = step { bufferChanged() }
306 return step
307 } catch {
308 return .failed("\(error)")
309 }
310 }
311 let url = URL(fileURLWithPath: path)
312 let name = url.lastPathComponent
313 do {
314 guard let bytes = try fileSystem.read(url) else { return .failed("\(name) no longer exists.") }
315 var state = DocumentState(bytes: bytes, defaults: defaults)
316 guard state.isEditable else { return .failed("\(name) isn't UTF-8, so it can't be changed.") }
317 guard matches(state.text) else { return stale }
318 let step = try state.run(command, selection: [offset..<offset], now: now, answers: answers, options: options)
319 if case .commit = step, state.isDirty, case .conflict = try saver.save(&state, to: url) {
320 return .failed("\(name) changed on disk; nothing was changed.")
321 }
322 return step
323 } catch {
324 return .failed("Can't change \(name): \(error.localizedDescription)")
325 }
326 }
327
328 // MARK: - External work
329
330 /// Recalculates a table in Emacs from a snapshot of the buffer, then replaces the table
331 /// with Emacs's text if it hasn't changed meanwhile. Returns a message for the echo area.
332 public func recalculateInEmacs(table: Range<Int>, point: Int, form: String) async -> String {
333 guard let buffer, let path else { return "No file is open." }
334 let snapshot = buffer.document.text as NSString
335 guard table.upperBound <= snapshot.length else { return "The table moved; try again." }
336 let old = snapshot.substring(with: NSRange(table))
337 let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
338 do {
339 let new = try await EmacsRunner.recalculateTable(text: snapshot as String, directory: directory, table: table, point: point, form: form)
340 guard let current = self.buffer, self.path == path else { return "The file was closed before Emacs finished." }
341 let text = current.document.text as NSString
342 guard table.upperBound <= text.length, text.substring(with: NSRange(table)) == old else {
343 return "The table changed while Emacs recalculated it; nothing was changed."
344 }
345 guard new != old else { return "Recalculated in Emacs" }
346 let result = EditResult(baseRevision: current.document.revision, edits: [TextEdit(range: table, replacement: new)])
347 if case .failed(let message) = current.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
348 bufferChanged()
349 return "Recalculated in Emacs"
350 } catch {
351 return "\(error)"
352 }
353 }
354
355 /// Runs a src block and writes its result under it, unless the block changed while it
356 /// ran. Returns a message for the echo area.
357 public func runBabel(_ job: BabelJob) async -> String {
358 guard let path, buffer != nil else { return "No file is open." }
359 let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
360 do {
361 let output = try await BabelRunner.run(job, fileDirectory: directory)
362 guard let current = self.buffer, self.path == path else { return "The file was closed before the block finished." }
363 let document = current.document
364 switch Babel.finish(job, output: output, text: document.text, settings: document.tree.settings) {
365 case .failure(.message(let message)):
366 return message
367 case .success(let edits):
368 guard !edits.isEmpty else { return job.finish.params.contains("silent") ? output.stdout : "Code block evaluation complete." }
369 let result = EditResult(baseRevision: document.revision, edits: edits)
370 if case .failed(let message) = current.perform(PrecomputedEdit(result), now: Date(), answers: [:]) { return message }
371 bufferChanged()
372 return "Code block evaluation complete."
373 }
374 } catch {
375 return "\(error)"
376 }
377 }
378
379 // MARK: - Locations
380
381 /// Opens the file of `location` if needed and asks the editor to show the heading. Offsets
382 /// are used only if the buffer matches what was indexed; otherwise the heading is found
383 /// again by position and title.
384 public func show(_ location: HeadingLocation) {
385 if path != location.path { open(location.path) }
386 guard let document else { return }
387 let hash = FileRecord.hash(document.mergeBase)
388 let offset: Int
389 if !isDirty, hash == location.contentHash {
390 offset = location.start
391 } else if location.ordinal < outline.count, outline[location.ordinal].title == location.title {
392 offset = outline[location.ordinal].start
393 } else if let entry = outline.first(where: { $0.title == location.title }) {
394 offset = entry.start
395 } else {
396 return
397 }
398 reveal(offset)
399 }
400
401 public func reveal(_ offset: Int) {
402 requestID += 1
403 revealRequest = (offset, requestID)
404 }
405
406 /// Called when the workspace sees the open file change on disk.
407 public func fileChanged(_ path: String) {
408 guard path == self.path, let buffer, let bytes = try? fileSystem.read(URL(fileURLWithPath: path)) else { return }
409 guard bytes != buffer.document.mergeBase else { return }
410 switch buffer.update({ $0.diskChanged(to: bytes) }) {
411 case .conflict:
412 autosave?.cancel()
413 conflict = "\(name) changed on disk, and the changes conflict with yours."
414 case .merged, .reloaded:
415 conflict = nil
416 case .unchanged:
417 break
418 }
419 refresh()
420 }
421}