Sources/Orgstar/ContentView.swift
1072 lines · 57866 bytes
1import AppKit
2import OrgApp
3import OrgCore
4import OrgEditorAppKit
5import OrgPresentation
6import OrgWorkspace
7import OrgIndex
8import SwiftUI
9import UniformTypeIdentifiers
10
11struct ContentView: View {
12 let workspace: WorkspaceModel
13 let session: DocumentSession
14 @Bindable var commands: AppCommands
15 let scheduler: ReminderScheduler?
16 let clock: ClockModel
17 @AppStorage("reminders") private var remindersEnabled = true
18 @AppStorage("reminderLead") private var reminderLead = 12
19 @AppStorage("clockIdleTime") private var clockIdleTime = 0
20 @AppStorage("agendaSubfolders") private var agendaSubfolders = false
21 @State private var reminderAgenda: AgendaModel?
22 @State private var trust = TrustStore()
23 @State private var hotKey: GlobalHotKey?
24 @State private var statusItem: ClockStatusItem?
25 @AppStorage("globalCapture") private var globalCapture = true
26 @State private var hour = 0
27 @AppStorage("saveMode") private var saveMode = SaveMode.automatic
28 @AppStorage("keymap") private var preset = KeymapPreset.emacs
29 @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
30 @State private var keymap = KeymapPreset.emacs.keymap
31 @AppStorage("tagsColumn") private var tagsColumn = -77
32 @AppStorage("headingAfterSubtree") private var headingAfterSubtree = true
33 @AppStorage("splitLine") private var splitLine = false
34 @AppStorage("alphabeticalLists") private var alphabeticalLists = true
35 @AppStorage("fillColumn") private var fillColumn = 80
36 @AppStorage("hiddenMarkers") private var hiddenMarkers = true
37 @AppStorage("prettyEntities") private var prettyEntities = true
38 @AppStorage("logDone") private var logDone = "nil"
39 @AppStorage("logIntoDrawer") private var logIntoDrawer = ""
40 @AppStorage("logReschedule") private var logReschedule = "nil"
41 @AppStorage("logRedeadline") private var logRedeadline = "nil"
42 @AppStorage("useSpeedCommands") private var useSpeedCommands = false
43 @AppStorage("startupWithInlineImages") private var startupWithInlineImages = false
44 @AppStorage("startupIndented") private var startupIndented = true
45 @AppStorage("hideLeadingStars") private var hideLeadingStars = false
46 @AppStorage("startupAlignAllTables") private var startupAlignAllTables = false
47 @AppStorage("startupTruncated") private var startupTruncated = false
48 @AppStorage("spellCheck") private var spellCheck = false
49 @AppStorage("electricPair") private var electricPair = true
50 @AppStorage("hideDrawerStartup") private var hideDrawerStartup = true
51 @AppStorage("hideBlockStartup") private var hideBlockStartup = false
52 @AppStorage("enforceTodoDependencies") private var enforceTodoDependencies = false
53 @AppStorage("enforceTodoCheckboxDependencies") private var enforceTodoCheckboxDependencies = false
54
55 /// Bumped when user defaults change, so settings only config.toml has reach `options`.
56 @State private var defaultsChanges = 0
57 private var options: EditingOptions {
58 _ = defaultsChanges
59 var options = Preferences.options(
60 tagsColumn: tagsColumn, headingAfterSubtree: headingAfterSubtree, splitLine: splitLine, alphabeticalLists: alphabeticalLists,
61 fillColumn: fillColumn, hiddenMarkers: hiddenMarkers, prettyEntities: prettyEntities, logDone: logDone, logIntoDrawer: logIntoDrawer,
62 hideDrawerStartup: hideDrawerStartup, hideBlockStartup: hideBlockStartup, logReschedule: logReschedule, logRedeadline: logRedeadline,
63 useSpeedCommands: useSpeedCommands, startupWithInlineImages: startupWithInlineImages,
64 startupIndented: startupIndented, hideLeadingStars: hideLeadingStars, startupAlignAllTables: startupAlignAllTables,
65 startupTruncated: startupTruncated, spellCheck: spellCheck, electricPair: electricPair,
66 enforceTodoDependencies: enforceTodoDependencies, enforceTodoCheckboxDependencies: enforceTodoCheckboxDependencies
67 )
68 // The agenda files, for clock tables over `agenda` scopes.
69 options.agendaFiles = workspace.agendaFilePaths()
70 return options
71 }
72 /// A block being edited apart (`org-edit-special`).
73 @State private var blockEdit: BlockEditRequest?
74 /// A sheet a command opened: column view or the export dialog.
75 @State private var panel: Panel?
76
77 @State private var selectedFile: String?
78 /// A file that isn't text, shown as a preview instead of the open document.
79 @State private var previewPath: String?
80 @AppStorage("outlineShown") private var orgOutlineShown = true
81 @AppStorage("outlineWidth") private var outlineWidth = 220.0
82 @AppStorage("backlinksShown") private var backlinksShown = true
83 @AppStorage("inspectorShown") private var inspectorShown = false
84 @AppStorage("showMarkup") private var showMarkup = false
85 @AppStorage("showLineNumbers") private var showLineNumbers = true
86 @AppStorage("showHiddenFiles") private var showHiddenFiles = true
87 @AppStorage("ignoredFolders") private var ignoredFolders = ScanRules.defaultIgnoredFolders.sorted().joined(separator: " ")
88 @AppStorage("themeFont") private var themeFont = ""
89 @AppStorage("themeFontSize") private var themeFontSize = 13
90 @AppStorage("themeLineSpacing") private var themeLineSpacing = 2
91 @AppStorage("themeHeadingStep") private var themeHeadingStep = 1
92
93 /// The theme's colors from config.toml with the type settings.
94 private var theme: ThemeSpec {
95 var spec = ConfigSync.shared.theme
96 spec.font = themeFont
97 spec.fontSize = themeFontSize
98 spec.lineSpacing = themeLineSpacing
99 spec.headingSizeStep = themeHeadingStep
100 return spec
101 }
102 /// The outline for a file that isn't org, off until asked for.
103 @State private var plainOutlineShown = false
104 @State private var showingImport = false
105 @AppStorage("showTabBar") private var showTabBar = false
106 /// This window's panes.
107 @State private var window: WindowModel?
108
109 private var editorSettings: EditorSettings {
110 EditorSettings(keymap: keymap, modal: preset.isModal, optionAsMeta: OptionAsMeta(rawValue: optionAsMeta), options: options, showMarkup: showMarkup, showLineNumbers: showLineNumbers, theme: theme)
111 }
112
113 /// The pane that had the focus when a sheet opened, to act on when it closes.
114 @State private var sheetTarget: EditorPane?
115
116 /// Puts the focus back on the pane a sheet was opened from.
117 private func restoreSheetTarget() {
118 guard let target = sheetTarget, session.panes.contains(where: { $0 === target }) else { return }
119 sheetTarget = nil
120 session.focused = target
121 if let window = commands.store.window(of: target.id) { window.focused = target.id }
122 if let path = target.path, let textView = commands.store.textView(for: target.id, path: path) {
123 textView.window?.makeFirstResponder(textView)
124 commands.editor = commands.store.editor(for: path)
125 }
126 }
127
128 /// The window holding the focused pane: this one, or an editor window.
129 private var paneWindow: WindowModel? {
130 commands.store.window(of: session.focused.id) ?? window
131 }
132
133 /// Gives the focused pane's text view the keyboard, after a pane command moved the focus.
134 private func focusPane(_ window: WindowModel) {
135 let pane = window.focusedPane
136 session.focused = pane
137 if let path = pane.path, let textView = commands.store.textView(for: pane.id, path: path) {
138 textView.window?.makeFirstResponder(textView)
139 commands.editor = commands.store.editor(for: path)
140 } else {
141 commands.editor = nil
142 }
143 }
144 /// Carets of restored buffers, shown when each first shows.
145 @State private var pendingCarets: [String: Int] = [:]
146 @State private var query = ""
147 @FocusState private var searchFocused: Bool
148 @Environment(\.openWindow) private var openWindow
149 @Environment(\.openSettings) private var openSettings
150
151 /// Whether the outline pane shows: remembered for org files, hidden by default for
152 /// other files, and always shown while search results are up.
153 private var outlineShown: Bool {
154 !query.isEmpty || (previewPath == nil && (session.isOrg ? orgOutlineShown : plainOutlineShown))
155 }
156
157 private func toggleOutline() {
158 if session.isOrg { orgOutlineShown.toggle() } else { plainOutlineShown.toggle() }
159 }
160
161 @ViewBuilder
162 private var detail: some View {
163 if let previewPath {
164 FilePreview(path: previewPath)
165 } else if !session.openPaths.isEmpty, let window {
166 PaneLayoutView(layout: window.layout, window: window) { pane in
167 PaneCell(pane: pane, window: window, session: session, commands: commands, showTabBar: showTabBar, onAppCommand: perform)
168 }
169 .safeAreaInset(edge: .bottom, spacing: 0) {
170 VStack(spacing: 0) {
171 ModeLine(session: session, commands: commands, clock: clock, perform: perform)
172 EchoArea(commands: commands)
173 }
174 }
175 } else {
176 ContentUnavailableView(
177 workspace.roots.isEmpty ? "Add a folder of org files" : "Choose a file",
178 systemImage: "doc.text",
179 description: Text(workspace.roots.isEmpty ? "File ▸ Add Folder… (⇧⌘O)" : "Or press ⌘P to open one by name.")
180 )
181 }
182 }
183
184 @ToolbarContentBuilder
185 private var toolbarItems: some ToolbarContent {
186 ToolbarItem(placement: .navigation) {
187 Button(outlineShown ? "Hide Outline" : "Show Outline", systemImage: "list.bullet.indent") { toggleOutline() }
188 .help(outlineShown ? "Hide the outline (⌥⌘O)" : "Show the outline (⌥⌘O)")
189 .disabled(!query.isEmpty || previewPath != nil || session.path == nil)
190 }
191 if workspace.isIndexing {
192 ToolbarItem { ProgressView().controlSize(.small) }
193 }
194 if let running = clock.running {
195 ToolbarItem {
196 Menu {
197 Button("Clock Out") { perform("app.clock.out") }
198 Button("Cancel Clock") { perform("app.clock.cancel") }
199 Button("Go to Clocked Entry") { perform("app.clock.goto") }
200 Divider()
201 Button("Clock In to Recent Entry…") { perform("app.clock.in-recent") }
202 Button("Go to Recent Clocked Entry…") { perform("app.clock.goto-recent") }
203 RecentClocks(clock: clock) { perform($0) }
204 } label: {
205 TimelineView(.periodic(from: .now, by: 30)) { context in
206 Text("⏱ \(running.heading) \(clockElapsed(running, now: context.date))").lineLimit(1)
207 }
208 }
209 .help("Clocked in since \(running.startedAt.formatted(date: .omitted, time: .shortened))")
210 }
211 }
212 if session.conflict != nil {
213 ToolbarItem {
214 Button("Conflict", systemImage: "exclamationmark.triangle") { commands.showingConflict = true }
215 .help("The file changed on disk, and the changes conflict with yours")
216 }
217 }
218 }
219
220 private var main: some View {
221 NavigationSplitView {
222 Sidebar(workspace: workspace, session: session, selection: $selectedFile) { commands.showingFolderPicker = true }
223 .navigationSplitViewColumnWidth(min: 200, ideal: 260)
224 } detail: {
225 HStack(spacing: 0) {
226 if outlineShown {
227 Group {
228 if query.isEmpty {
229 VStack(spacing: 0) {
230 OutlineColumn(session: session)
231 if backlinksShown, session.isOrg {
232 Divider()
233 BacklinksPane(workspace: workspace, session: session, commands: commands) { location in
234 selectedFile = location.path
235 session.show(location)
236 }
237 .frame(height: 200)
238 }
239 }
240 } else {
241 SearchResults(results: workspace.search(query, overlay: workspace.overlay(session.openDocuments))) { location in
242 selectedFile = location.path
243 session.show(location)
244 }
245 }
246 }
247 .frame(width: CGFloat(outlineWidth))
248 PaneDivider(width: $outlineWidth, range: 160...400)
249 }
250 detail
251 .frame(maxWidth: .infinity)
252 .inspector(isPresented: $inspectorShown) {
253 InspectorPane(session: session, commands: commands)
254 .inspectorColumnWidth(min: 240, ideal: 340, max: 600)
255 }
256 }
257 }
258 .navigationTitle(previewPath.map { ($0 as NSString).lastPathComponent } ?? session.path.map(session.bufferName) ?? "orgstar")
259 .navigationSubtitle(session.isReadOnly ? "Read-only: not UTF-8" : "")
260 .searchable(text: $query, placement: .toolbar, prompt: "Search notes")
261 .searchFocused($searchFocused)
262 .toolbar { toolbarItems }
263 .onChange(of: session.path) { plainOutlineShown = false }
264 .onChange(of: ScanRules(hiddenFiles: showHiddenFiles, ignoredFolders: Set(ignoredFolders.split(separator: " ").map(String.init))), initial: true) { _, rules in
265 workspace.scanRules = rules
266 }
267 .onChange(of: selectedFile) { old, path in
268 guard let path else { return }
269 if !DocumentSession.isOrgPath(path), !FileTypes.isText(path) {
270 previewPath = path
271 return
272 }
273 previewPath = nil
274 guard path != session.path else { return }
275 session.open(path)
276 }
277 .onChange(of: session.path) {
278 // Buffers switched by keys show in the sidebar too; a restored caret shows once.
279 if let path = session.path, selectedFile != path { selectedFile = path }
280 if let path = session.path, let caret = pendingCarets.removeValue(forKey: path) { session.reveal(caret) }
281 BufferRestore.save(session)
282 // Syncthing's conflict copies of the file.
283 let copies = session.syncConflictCopies().count
284 if copies > 0 { commands.show("\(copies) sync conflict \(copies == 1 ? "copy" : "copies") of this file; Resolve Sync Conflicts compares them.") }
285 }
286 .onChange(of: session.openPaths) { _, paths in
287 BufferRestore.save(session)
288 for path in commands.store.editors.keys where !paths.contains(path) { commands.store.releasePath(path) }
289 }
290 .onChange(of: editorSettings, initial: true) { _, settings in commands.editorSettings = settings }
291 .onAppear {
292 commands.externalHandler = runExternal
293 // `org-clock-out-when-done`, and the notification when the Effort runs out.
294 clock.notifications = SystemReminderCenter.isAvailable ? SystemReminderCenter() : nil
295 session.textChanged = { [weak session, weak clock, weak commands] path in
296 guard let session, let clock, let message = clock.textChanged(path, session) else { return }
297 commands?.show(message)
298 }
299 clock.remindAtEffort(session)
300 commands.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] }
301 commands.mainWindowOpen = true
302 if let stale = window { commands.store.windows.removeAll { $0 === stale } }
303 // The session's first pane the first time; a new one showing the focused buffer
304 // when the window opens again.
305 let pane: EditorPane
306 if commands.store.window(of: session.panes[0].id) == nil, window == nil {
307 pane = session.panes[0]
308 } else {
309 pane = session.makePane()
310 if let path = session.focused.path { session.open(path, in: pane) }
311 }
312 let model = WindowModel(session: session, pane: pane)
313 window = model
314 commands.store.windows.insert(model, at: 0)
315 model.focus(pane.id)
316 }
317 .onDisappear {
318 commands.mainWindowOpen = false
319 guard let model = window else { return }
320 for id in model.layout.panes { commands.store.releasePane(id) }
321 model.closeAll()
322 commands.store.windows.removeAll { $0 === model }
323 commands.editor = nil
324 }
325 .onChange(of: saveMode, initial: true) { _, mode in session.saveMode = mode }
326 .onChange(of: options, initial: true) { _, options in session.options = options }
327 .onReceive(NotificationCenter.default.publisher(for: UserDefaults.didChangeNotification)) { _ in defaultsChanges += 1 }
328 .onChange(of: preset, initial: true) { loadKeymap() }
329 .sheet(isPresented: $showingImport) { EmacsImportView(workspace: workspace) }
330 .sheet(item: $panel) { panel in
331 switch panel {
332 case .columns(_, let view):
333 ColumnViewSheet(view: view, run: runInColumnView, document: { session.document.map { ($0.text, $0.tree) } }) { offset in
334 commands.editor?.reveal(offset)
335 }
336 case .export(_, let source):
337 ExportSheet(source: source, inSubtree: exportSubtreeAvailable, target: exportTarget) { format, destination, open, subtree, bodyOnly in
338 export(format, to: destination, open: open, subtree: subtree, bodyOnly: bodyOnly)
339 }
340 case .plot(_, let plot):
341 PlotSheet(content: .chart(plot))
342 case .plotImage(_, let url):
343 PlotSheet(content: .image(url))
344 case .conflict:
345 ConflictSheet(session: session)
346 case .syncCopies:
347 SyncConflictSheet(session: session) { commands.show($0) }
348 case .recovery:
349 RecoverySheet(session: session) { commands.show($0) }
350 }
351 }
352 .sheet(item: $blockEdit) { request in
353 BlockEditorView(edit: request.edit) { content in
354 blockEdit = nil
355 guard let content else { return }
356 commands.editor?.perform(ReplaceBlockLines(edit: request.edit, content: content))
357 }
358 }
359 .sheet(isPresented: $commands.showingPalette) {
360 PaletteView(commands: commands) { id in
361 commands.showingPalette = false
362 // After the sheet closes, so app commands can present their own, and in the
363 // pane that had the focus when it opened: closing a sheet makes this window key.
364 DispatchQueue.main.async {
365 restoreSheetTarget()
366 perform(id)
367 }
368 }
369 }
370 .onChange(of: commands.showingPalette) { _, showing in if showing { sheetTarget = session.focused } }
371 .onChange(of: commands.showingQuickOpen) { _, showing in if showing { sheetTarget = session.focused } }
372 .onChange(of: session.conflict) { _, conflict in
373 if conflict != nil { commands.showingConflict = true }
374 }
375 .onChange(of: commands.showingConflict) { _, showing in
376 guard showing else { return }
377 commands.showingConflict = false
378 if session.conflict != nil { panel = .conflict(UUID()) }
379 }
380 .onChange(of: workspace.changedFile?.version) { fileChangedOnDisk() }
381 }
382
383 /// A column view edit at the heading starting at `start` in the open file.
384 private func runInColumnView(_ command: any OrgCommand, _ start: Int, _ answers: [String: String]) -> CommandStep {
385 guard let path = session.path else { return .failed("No file is open") }
386 return session.perform(command, path: path, at: start, expect: nil, answers: answers)
387 }
388
389 /// An open file takes in what changed on disk, and a clock started or stopped in Emacs
390 /// becomes the one shown.
391 private func fileChangedOnDisk() {
392 guard let path = workspace.changedFile?.path else { return }
393 session.fileChanged(path)
394 if path.hasSuffix(".org") { syncClock(paths: [path]) }
395 }
396
397 /// Open clocks in `paths`: at launch and as folders load, the agenda files.
398 private func syncClock(paths: [String]) {
399 guard !workspace.files.isEmpty, let message = clock.sync(session, paths: paths) else { return }
400 commands.show(message)
401 }
402
403 var body: some View {
404 main
405 .task(id: workspace.files.count) { syncClock(paths: workspace.agendaFilePaths()) }
406 .onChange(of: ClockMenuState(running: clock.running, history: clock.history), initial: true) { _, state in
407 if statusItem == nil { statusItem = ClockStatusItem { commands.run($0) } }
408 statusItem?.update(state.running, recent: state.history.map(\.title))
409 }
410 .onChange(of: globalCapture, initial: true) { _, enabled in
411 hotKey?.unregister()
412 hotKey = enabled ? GlobalHotKey { perform("app.capture") } : nil
413 }
414 .onChange(of: commands.runRequest?.serial, initial: true) {
415 if let id = commands.runRequest?.id { perform(id) }
416 }
417 .onChange(of: ConfigSync.shared.problems, initial: true) { _, problems in
418 if let first = problems.first {
419 commands.show(first + (problems.count > 1 ? " (and \(problems.count - 1) more)" : ""))
420 }
421 }
422 .onChange(of: ConfigSync.shared.changedFile?.serial) {
423 if ConfigSync.shared.changedFile?.name == "keymap.toml" { loadKeymap() }
424 }
425 .onChange(of: commands.jumpRequest?.id) {
426 guard let request = commands.jumpRequest else { return }
427 if request.path != session.path {
428 session.open(request.path)
429 selectedFile = request.path
430 }
431 session.reveal(request.offset)
432 }
433 .onChange(of: commands.focusSearch) { _, focus in
434 if focus {
435 searchFocused = true
436 commands.focusSearch = false
437 }
438 }
439 .fileImporter(isPresented: $commands.showingFolderPicker, allowedContentTypes: [.folder]) { result in
440 guard case .success(let url) = result else { return }
441 Task {
442 do { try await workspace.addRoot(url) } catch { workspace.lastError = error.localizedDescription }
443 }
444 }
445 .sheet(isPresented: $commands.showingQuickOpen) {
446 QuickOpenView(workspace: workspace) { entry in
447 commands.showingQuickOpen = false
448 DispatchQueue.main.async {
449 restoreSheetTarget()
450 selectedFile = entry.path
451 if selectedFile == entry.path { session.open(entry.path) }
452 }
453 }
454 }
455 .alert("orgstar", isPresented: errorShown) {
456 Button("OK") {
457 workspace.lastError = nil
458 session.lastError = nil
459 }
460 } message: {
461 Text(workspace.lastError ?? session.lastError ?? "")
462 }
463 .task(id: ReminderKey(
464 enabled: remindersEnabled, lead: reminderLead, subfolders: agendaSubfolders, files: workspace.files.count,
465 changed: workspace.changedFile?.version, edits: session.editVersion, hour: hour
466 )) {
467 await updateReminders()
468 }
469 .task {
470 while !Task.isCancelled {
471 try? await Task.sleep(for: .seconds(3600))
472 hour += 1
473 }
474 }
475 // `org-resolve-clocks-if-idle`, checked every minute while a clock runs.
476 .task(id: "\(clock.running?.start ?? "") \(clockIdleTime)") {
477 guard clock.running != nil, clockIdleTime > 0 else { return }
478 while !Task.isCancelled {
479 try? await Task.sleep(for: .seconds(60))
480 guard !Task.isCancelled, clock.running != nil, !clock.isResolving else { continue }
481 let idle = ClockIdle.seconds()
482 guard idle > Double(clockIdleTime * 60) else { continue }
483 NSApp.requestUserAttention(.informationalRequest)
484 report(await clock.resolveIdle(session, idleSince: Date().addingTimeInterval(-idle), ask: askClock))
485 }
486 }
487 .task {
488 DevelopmentHooks.scheduleSnapshot()
489 pendingCarets = BufferRestore.restore(session)
490 if let path = session.path, let caret = pendingCarets.removeValue(forKey: path) { session.reveal(caret) }
491 // Files handed over at launch open after the restored buffers, and show.
492 for path in AppDelegate.pendingOpens { session.open(path) }
493 AppDelegate.pendingOpens = []
494 for link in AppDelegate.pendingLinks + [DevelopmentHooks.urlToOpen].compactMap({ $0 }) { commands.handle(protocolURL: link) }
495 AppDelegate.pendingLinks = []
496 if let path = DevelopmentHooks.fileToOpen { selectedFile = path }
497 if let root = DevelopmentHooks.rootToAdd { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
498 if let commandList = DevelopmentHooks.commandToRun {
499 // The file opened above needs its editor first.
500 for _ in 0..<20 where DevelopmentHooks.fileToOpen != nil && commands.editor == nil { try? await Task.sleep(for: .milliseconds(100)) }
501 for command in commandList.split(separator: ",") { perform(String(command)) }
502 for answer in DevelopmentHooks.answers {
503 for _ in 0..<20 where commands.prompt == nil { try? await Task.sleep(for: .milliseconds(100)) }
504 commands.answer(answer)
505 }
506 }
507 if let id = DevelopmentHooks.windowToOpen {
508 if id == "settings" { openSettings() } else { openWindow(id: id) }
509 }
510 await workspace.refresh()
511 workspace.startWatching()
512 }
513 }
514
515 /// The selection, or the whole file without one, on the clipboard as HTML, RTF and plain
516 /// text, to paste formatted into mail and documents.
517 private func copyRichText() {
518 guard let path = session.path, let whole = session.document?.text, let editor = commands.editor else { return commands.show("No file is open") }
519 let defaults = Preferences.orgSettings.resolvingSetupFiles(in: whole, path: path, read: OrgSettings.readFile)
520 let selection = editor.context().selection.first { !$0.isEmpty }
521 let selected = selection.map { (whole as NSString).substring(with: NSRange($0)) }
522 let url = URL(fileURLWithPath: path)
523 let html = HTMLExport.page(
524 selected ?? whole, fallbackTitle: url.deletingPathExtension().lastPathComponent, settings: defaults, path: path, bodyOnly: selected != nil,
525 codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme)
526 )
527 do {
528 try RichTextExport.copy(html: html, directory: url.deletingLastPathComponent())
529 commands.show(selected == nil ? "Copied the file as rich text" : "Copied the selection as rich text")
530 } catch {
531 commands.show("\(error)")
532 }
533 }
534
535 /// Whether the caret is in a heading's subtree, which the export dialog can export alone.
536 private var exportSubtreeAvailable: Bool {
537 guard let text = session.document?.text, let caret = commands.editor?.context().caret else { return false }
538 return ExportScope.subtree(text, at: caret) != nil
539 }
540
541 /// Where an export goes by default: `#+EXPORT_FILE_NAME`, or the subtree's
542 /// `EXPORT_FILE_NAME`, else beside the file, with `ext`.
543 private func exportTarget(_ ext: String, subtree: Bool) -> URL {
544 let path = session.path ?? ""
545 let text = session.document?.text ?? ""
546 let caret = subtree ? commands.editor?.context().caret : nil
547 return ExportScope.output(for: URL(fileURLWithPath: path), name: ExportScope.fileName(text, subtreeAt: caret), extension: ext)
548 }
549
550 /// Writes the export where `#+EXPORT_FILE_NAME` says or beside the file, as Emacs's export
551 /// dispatcher does, or to `destination`, and opens it with `open`. `subtree` exports the
552 /// subtree at the caret alone; `bodyOnly` leaves out the title and page wrapper.
553 private func export(_ format: String, to destination: URL? = nil, open: Bool = false, subtree: Bool = false, bodyOnly: Bool = false) {
554 if format == "icalendar-agenda" || format == "icalendar-combined" { return exportAgendaCalendars(combined: format == "icalendar-combined") }
555 guard let path = session.path, var text = session.document?.text else {
556 commands.show("No file is open")
557 return
558 }
559 let url = URL(fileURLWithPath: path)
560 let base = url.deletingPathExtension()
561 let defaults = Preferences.orgSettings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
562 let open = open || format == "html-open"
563 let caret = commands.editor?.context().caret ?? 0
564 let whole = text
565 if subtree {
566 guard let narrowed = ExportScope.subtree(text, at: caret, settings: defaults) else { return commands.show("Not in a subtree") }
567 text = narrowed
568 }
569 switch format {
570 case "icalendar":
571 do {
572 let target = try ICalendarFiles.export(whole, path: path, settings: defaults, options: OrgPreferences.icalendarOptions(),
573 subtree: subtree ? caret : nil, destination: destination)
574 commands.show("Exported to \(target.lastPathComponent)")
575 if open { NSWorkspace.shared.open(target) }
576 } catch {
577 commands.show("Can't export: \(error.localizedDescription)")
578 }
579 case "html", "html-open", "markdown":
580 let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
581 let target = destination ?? ExportScope.output(for: url, name: name, extension: format == "markdown" ? "md" : "html")
582 let content = format == "markdown"
583 ? MarkdownExport.document(text, settings: defaults, path: path, bodyOnly: bodyOnly)
584 : HTMLExport.page(
585 text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path, bodyOnly: bodyOnly,
586 codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme)
587 )
588 do {
589 try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
590 try content.write(to: target, atomically: true, encoding: .utf8)
591 commands.show("Exported to \(target.lastPathComponent)")
592 if open { NSWorkspace.shared.open(target) }
593 } catch {
594 commands.show("Can't write \(target.lastPathComponent): \(error.localizedDescription)")
595 }
596 case "print-pdf", "docx", "rtf", "plain-text":
597 let ext = ["print-pdf": "pdf", "plain-text": "txt"][format] ?? format
598 let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
599 let target = destination ?? ExportScope.output(for: url, name: name, extension: ext)
600 let html = HTMLExport.page(
601 text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path,
602 codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme)
603 )
604 let directory = url.deletingLastPathComponent()
605 if format == "print-pdf" { commands.show("Exporting to PDF…") }
606 Task {
607 do {
608 let data: Data
609 switch format {
610 case "print-pdf": data = try await PDFExport.pdf(html: html, directory: directory)
611 case "docx": data = try RichTextExport.docx(RichTextExport.attributed(html: html, directory: directory))
612 case "rtf": data = try RichTextExport.rtf(RichTextExport.attributed(html: html, directory: directory))
613 default: data = Data(RichTextExport.plain(try RichTextExport.attributed(html: html, directory: directory)).utf8)
614 }
615 try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
616 try data.write(to: target, options: .atomic)
617 commands.show("Exported to \(target.lastPathComponent)")
618 if open { NSWorkspace.shared.open(target) }
619 } catch {
620 commands.show("Can't export \(target.lastPathComponent): \(error)")
621 }
622 }
623 default:
624 let functions = ["pdf": "org-latex-export-to-pdf", "odt": "org-odt-export-to-odt", "latex": "org-latex-export-to-latex", "text": "org-ascii-export-to-ascii"]
625 guard let function = functions[format] else { return }
626 commands.show("Exporting with Emacs…")
627 commands.runInEmacs {
628 do {
629 // Emacs narrows to the subtree and reads EXPORT_FILE_NAME itself.
630 let point = subtree ? (whole as NSString).substring(to: min(caret, (whole as NSString).length)).unicodeScalars.count + 1 : nil
631 var written = URL(fileURLWithPath: try await EmacsRunner.export(
632 text: whole, path: path, function: function, subtree: point, bodyOnly: bodyOnly
633 ))
634 if let destination, destination.standardizedFileURL != written.standardizedFileURL {
635 try? FileManager.default.removeItem(at: destination)
636 try FileManager.default.moveItem(at: written, to: destination)
637 written = destination
638 }
639 commands.show("Exported to \(written.lastPathComponent)")
640 if open { NSWorkspace.shared.open(written) }
641 } catch is CancellationError {
642 commands.show("Export canceled")
643 } catch {
644 commands.show("\(error)")
645 }
646 }
647 }
648 }
649
650 /// `org-icalendar-export-agenda-files`, or with `combined`, `org-icalendar-combine-agenda-files`.
651 private func exportAgendaCalendars(combined: Bool) {
652 let paths = workspace.agendaFilePaths()
653 let read = { (path: String) -> (text: String, settings: OrgSettings)? in
654 guard let text = session.openDocuments.first(where: { $0.path == path })?.document.text ?? (try? String(contentsOfFile: path, encoding: .utf8)) else { return nil }
655 return (text, Preferences.orgSettings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile))
656 }
657 do {
658 let options = OrgPreferences.icalendarOptions()
659 if combined {
660 let url = try ICalendarFiles.combine(paths, to: OrgPreferences.icalendarCombinedFile(), options: options, read: read)
661 commands.show("Exported \(paths.count) agenda files to \(url.lastPathComponent)")
662 } else {
663 let written = try ICalendarFiles.exportEach(paths, options: options, read: read)
664 commands.show("Exported \(written.count) agenda files to iCalendar")
665 }
666 } catch {
667 commands.show("Can't export: \(error.localizedDescription)")
668 }
669 }
670
671 /// `org-plot/gnuplot` for the table at the caret: through gnuplot when it's installed, as
672 /// Emacs runs it, else drawn here; written to `file:` when the options name one, else shown.
673 private func plotTable() {
674 guard let editor = commands.editor, let path = session.path else { return commands.show("No file is open") }
675 let context = editor.context()
676 let plot: TablePlot.Plot
677 do { plot = try TablePlot.plot(context.text, at: context.caret) } catch { return commands.show("\(error)") }
678 let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
679 if let gnuplot = PlotOutput.gnuplot {
680 commands.show("Plotting with gnuplot…")
681 Task {
682 do {
683 let image = try await PlotOutput.runGnuplot(plot, directory: directory, gnuplot: gnuplot)
684 if plot.options.file == nil { panel = .plotImage(UUID(), image) } else { plotWritten(image, editor: editor) }
685 } catch {
686 commands.show("\(error)")
687 }
688 }
689 } else if let url = PlotOutput.file(plot, directory: directory) {
690 do {
691 try PlotOutput.write(plot, to: url)
692 plotWritten(url, editor: editor)
693 } catch {
694 commands.show("\(error)")
695 }
696 } else {
697 panel = .plot(UUID(), plot)
698 }
699 }
700
701 /// The image is where `file:` says; a link to it shows it again.
702 private func plotWritten(_ url: URL, editor: OrgEditor) {
703 commands.show("Plot written to \(url.lastPathComponent)")
704 if editor.showsImages { editor.refreshImages() }
705 }
706
707 /// `org-publish`, `org-publish-all`, `org-publish-current-file` and
708 /// `org-publish-current-project`, with the projects in config.toml.
709 private func publish(_ id: String) {
710 let config = (try? String(contentsOf: UserConfig.file("config.toml"), encoding: .utf8)) ?? ""
711 let loaded = Publish.projects(fromConfig: config, root: workspace.rootPaths.first)
712 if let problem = loaded.problems.first { commands.show(problem) }
713 guard !loaded.projects.isEmpty else { return commands.show("No [[publish]] projects in config.toml") }
714 let read = { (path: String) -> String? in
715 session.openDocuments.first { $0.path == path }?.document.text ?? (try? String(contentsOfFile: path, encoding: .utf8))
716 }
717 let codeStyle = HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme)
718 func run(_ chosen: [PublishProject], only: String? = nil) {
719 do {
720 let report = try Publish.publish(chosen, all: loaded.projects, only: only, read: read) { function, text, path, bodyOnly in
721 let settings = Preferences.orgSettings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
722 if function == "org-md-publish-to-md" { return MarkdownExport.document(text, settings: settings, path: path, bodyOnly: bodyOnly) }
723 let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
724 return HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, bodyOnly: bodyOnly, codeStyle: codeStyle)
725 }
726 commands.show("Published \(report.published.count) files" + (report.skipped.isEmpty ? "" : ", \(report.skipped.count) up to date"))
727 } catch {
728 commands.show("\(error)")
729 }
730 }
731 let current = session.path.map { Publish.projects(containing: $0, in: loaded.projects) } ?? []
732 switch id {
733 case "app.publish.all":
734 run(loaded.projects)
735 case "app.publish.current-file":
736 guard let path = session.path, !current.isEmpty else { return commands.show("File is not part of any known project") }
737 run([current[0]], only: path)
738 case "app.publish.current-project":
739 guard !current.isEmpty else { return commands.show("File is not part of any known project") }
740 run([current[0]])
741 default:
742 let names = loaded.projects.map(\.name)
743 commands.ask(Prompt(key: "project", message: "Publish project:", choices: names)) { answer in
744 guard let answer, let project = loaded.projects.first(where: { $0.name == answer }) else { return }
745 run([project])
746 }
747 }
748 }
749
750 /// Work a command hands to the platform: tables recalculated in Emacs.
751 private func runExternal(_ request: ExternalRequest) {
752 switch request {
753 case .openLink(let link):
754 if let message = LinkOpener.open(link, session: session, workspace: workspace) { commands.show(message) }
755 // `org-occur` for a regexp link, once the editor shows the file.
756 if let regexp = Links.regexpSearch(link) {
757 DispatchQueue.main.async { commands.editor?.perform(SparseTreeCommand(), answers: ["sparse": "/", "regexp": regexp]) }
758 }
759 case .tangle(let scope):
760 commands.show(session.tangle(scope))
761 case .agenda(let start, let days):
762 commands.agendaRequest = (start, days)
763 openWindow(id: "agenda")
764 case .editBlock(let edit):
765 blockEdit = BlockEditRequest(edit: edit)
766 case .columnView(let view):
767 panel = .columns(UUID(), view)
768 case .emacsTable(let table, let point, let form, let reason, let lisp):
769 let run = {
770 commands.show("Recalculating in Emacs (\(reason))…")
771 commands.runInEmacs { commands.show(await session.recalculateInEmacs(table: table, point: point, form: form)) }
772 }
773 guard lisp, let path = session.path, let text = session.document?.text else { return run() }
774 let content = (text as NSString).substring(with: NSRange(location: table.lowerBound, length: min((text as NSString).length, table.upperBound + 2000) - table.lowerBound))
775 if trust.isTrusted(path: path, content: content) { return run() }
776 commands.ask(Prompt(key: "confirm", message: "This table's formulas run Lisp. Run them? (yes, no, always)", choices: ["yes", "no", "always"])) { answer in
777 switch answer {
778 case "always":
779 trust.trust(path: path, content: content)
780 run()
781 case "yes": run()
782 default: commands.show("Not recalculated")
783 }
784 }
785 case .babel(let job):
786 let run = {
787 commands.show("Running \(job.language) block… (⌘. to cancel)")
788 session.startBabel(job) { commands.show($0) }
789 }
790 guard let path = session.path else { return }
791 if !job.alwaysAsk, trust.isTrusted(path: path, content: job.blockText) { return run() }
792 let choices = job.alwaysAsk ? ["yes", "no"] : ["yes", "no", "always"]
793 commands.ask(Prompt(key: "confirm", message: "Run this \(job.language) block? (\(choices.joined(separator: ", ")))", choices: choices)) { answer in
794 switch answer {
795 case "always":
796 trust.trust(path: path, content: job.blockText)
797 run()
798 case "yes": run()
799 default: commands.show("Not run")
800 }
801 }
802 }
803 }
804
805 private struct ReminderKey: Hashable {
806 var enabled: Bool
807 var lead: Int
808 var subfolders: Bool
809 var files: Int
810 var changed: Int?
811 var edits: Int
812 var hour: Int
813 }
814
815 /// Sets the notifications for the next week's timed entries, once edits pause.
816 private func updateReminders() async {
817 guard let scheduler else { return }
818 guard remindersEnabled else {
819 await scheduler.clear()
820 return
821 }
822 try? await Task.sleep(for: .seconds(2))
823 guard !Task.isCancelled, !workspace.files.isEmpty else { return }
824 let agenda = reminderAgenda ?? AgendaModel(workspace: workspace)
825 reminderAgenda = agenda
826 agenda.includeSubfolders = agendaSubfolders
827 let open = session.openTexts
828 let reminders = await agenda.reminders(open: open, lead: reminderLead)
829 guard !Task.isCancelled else { return }
830 await scheduler.reconcile(reminders)
831 }
832
833 private func loadKeymap() {
834 let loaded = KeymapLoader.load(preset, commands: Set(EditorCommands.all.map(\.id)))
835 keymap = loaded.keymap
836 commands.keymap = loaded.keymap
837 commands.modal = preset.isModal
838 if let first = loaded.problems.first {
839 let more = loaded.problems.count > 1 ? " (and \(loaded.problems.count - 1) more)" : ""
840 commands.show("keymap.toml: \(first)\(more)")
841 }
842 }
843
844 /// `SPC b b`: open buffers, most recent first, by name (with the folder when names repeat).
845 private func switchBuffer() {
846 let paths = session.recentPaths.dropFirst() + session.recentPaths.prefix(1)
847 let labels = paths.map(session.bufferName)
848 guard !labels.isEmpty else { return commands.show("No buffers are open") }
849 commands.ask(Prompt(key: "buffer", message: "Switch to buffer:", choices: labels)) { answer in
850 guard let answer, let index = labels.firstIndex(of: answer) else { return }
851 session.open(Array(paths)[index])
852 }
853 }
854
855 /// Runs a command from a key, the palette or the Org menu.
856 private func perform(_ id: String) {
857 let orgOnly = ["app.refile", "app.refile.copy", "app.archive", "app.clock.in", "app.clock.default", "app.copy-rich-text"].contains(id) || (id.hasPrefix("app.export.") && !id.hasPrefix("app.export.icalendar-")) || id.hasPrefix("org.")
858 if orgOnly, !session.isOrg {
859 commands.show("Not an org file")
860 return
861 }
862 switch id {
863 case "app.save":
864 if !session.save(), session.conflict != nil { commands.showingConflict = true }
865 case "app.quit": NSApp.terminate(nil)
866 case "app.save-all":
867 if !session.saveAll(), session.conflict != nil { commands.showingConflict = true }
868 case "app.buffer.switch": switchBuffer()
869 case "app.buffer.next": session.cycle(1)
870 case "app.buffer.previous": session.cycle(-1)
871 case "app.buffer.last": session.showPrevious()
872 case "app.buffer.kill":
873 guard let path = session.path else {
874 NSApp.keyWindow?.performClose(nil)
875 return
876 }
877 if UnsavedChanges.resolve(session) { session.kill(path) }
878 case "app.buffer.kill-others":
879 let others = session.openPaths.filter { $0 != session.path }
880 if UnsavedChanges.resolve(session, paths: others) { others.forEach(session.kill) }
881 case "app.buffer.kill-all":
882 let all = session.openPaths
883 if UnsavedChanges.resolve(session, paths: all) { all.forEach(session.kill) }
884 case "app.toggle-tab-bar": showTabBar.toggle()
885 case "app.split-below": paneWindow?.split(.vertical)
886 case "app.split-right": paneWindow?.split(.horizontal)
887 case "app.pane-close":
888 guard let window = paneWindow, window.paneCount > 1 else { return commands.show("Attempt to delete the only pane") }
889 commands.store.releasePane(window.focused)
890 window.close(window.focused)
891 focusPane(window)
892 case "app.pane-only":
893 guard let window = paneWindow else { return }
894 for id in window.layout.panes where id != window.focused { commands.store.releasePane(id) }
895 window.closeOthers()
896 focusPane(window)
897 case "app.pane-next":
898 guard let window = paneWindow else { return }
899 window.focusNext()
900 focusPane(window)
901 case "app.window-new": openWindow(id: "editor")
902 case "app.babel.cancel":
903 if session.isRunningBabel {
904 session.cancelBabel()
905 } else if let task = commands.emacsTask {
906 task.cancel()
907 } else {
908 commands.show("Nothing is running")
909 }
910 case "app.toggle-outline": toggleOutline()
911 case "app.toggle-backlinks": backlinksShown.toggle()
912 case "app.toggle-inspector": inspectorShown.toggle()
913 case "app.toggle-markup": showMarkup.toggle()
914 case "app.toggle-line-numbers": showLineNumbers.toggle()
915 case "app.import-emacs": showingImport = true
916 case "app.edit-config": commands.jump(path: UserConfig.configFile.path, offset: 0)
917 case "app.quick-open": commands.showingQuickOpen = true
918 case "app.palette": commands.showingPalette = true
919 case "app.search": commands.focusSearch = true
920 case "app.reload-keymap":
921 loadKeymap()
922 commands.show("Keymap reloaded")
923 case "app.refile", "app.refile.copy":
924 let keep = id == "app.refile.copy"
925 let targets = workspace.refileTargets(openPath: session.path, document: session.document)
926 commands.ask(Prompt(key: "refile", message: keep ? "Copy to:" : "Refile to:", choices: targets.map(\.label))) { answer in
927 guard let answer else { return }
928 if let target = targets.first(where: { $0.label == answer }) {
929 if let message = session.refile(to: target, keep: keep) { commands.show(message) }
930 return
931 }
932 // `org-refile-allow-creating-parent-nodes`: `parent/new` adds the heading first.
933 let creating = OrgPreferences.refileSettings().creating
934 guard creating != .no, let (parent, child) = RefileSettings.newNode(answer, in: targets) else { return commands.show("Invalid target location") }
935 let create = {
936 switch session.createRefileChild(under: parent, title: child) {
937 case .success(let target): if let message = session.refile(to: target, keep: keep) { commands.show(message) }
938 case .failure(.message(let message)): commands.show(message)
939 }
940 }
941 guard creating == .confirm else { return create() }
942 commands.ask(Prompt(key: "confirm", message: "Create new node \"\(child)\"?", choices: ["yes", "no"])) { reply in
943 if reply == "yes" { create() }
944 }
945 }
946 case "app.refile.goto":
947 // `C-u C-c C-w`: the target heading, or the end of a file.
948 let targets = workspace.refileTargets(openPath: session.path, document: session.document)
949 commands.ask(Prompt(key: "refile", message: "Goto:", choices: targets.map(\.label))) { answer in
950 guard let answer, let target = targets.first(where: { $0.label == answer }) else { return }
951 commands.jump(path: target.path, offset: target.start ?? Int.max)
952 }
953 case "app.archive":
954 if let message = session.archive() { commands.show(message) }
955 case "app.table-import":
956 // `org-table-import`: a TSV, CSV or space-separated file becomes a table at point.
957 guard let editor = commands.editor else { return commands.show("No file is open") }
958 let panel = NSOpenPanel()
959 panel.allowedContentTypes = [.commaSeparatedText, .tabSeparatedText, .plainText]
960 guard panel.runModal() == .OK, let url = panel.url else { return }
961 guard let contents = try? String(contentsOf: url, encoding: .utf8) else { return commands.show("Can't read \(url.lastPathComponent)") }
962 editor.perform(ImportTable(contents: contents))
963 case "app.table-export":
964 // `org-table-export`: CSV for a .csv name, else TSV.
965 guard let editor = commands.editor else { return commands.show("No file is open") }
966 let context = editor.context()
967 guard ImportTable.exportText(context.text, at: context.caret, path: "") != nil else { return commands.show("No table at point") }
968 let panel = NSSavePanel()
969 panel.nameFieldStringValue = "table.csv"
970 guard panel.runModal() == .OK, let url = panel.url,
971 let text = ImportTable.exportText(context.text, at: context.caret, path: url.path) else { return }
972 do {
973 try text.write(to: url, atomically: true, encoding: .utf8)
974 commands.show("Export done.")
975 } catch {
976 commands.show("File not written: \(error.localizedDescription)")
977 }
978 case "org.subtree.paste":
979 guard let text = NSPasteboard.general.string(forType: .string) else { return commands.show("The clipboard is empty") }
980 commands.editor?.perform(PasteSubtree(text: text))
981 case "org.link.insert":
982 commands.editor?.perform(InsertLink(stored: commands.storedLinks, file: session.path))
983 case "org.link.store":
984 guard let editor = commands.editor, let path = session.path else { return commands.show("No method for storing a link from this buffer") }
985 commands.storeLink(Links.store(in: editor.context(), path: Links.abbreviate(path, home: NSHomeDirectory())))
986 case "org.id.store-link":
987 guard let editor = commands.editor, let path = session.path else { return }
988 if case .commit = editor.perform(CreateID()),
989 let link = Links.storeID(in: editor.context(), fileName: (path as NSString).lastPathComponent) {
990 commands.storeLink(link)
991 }
992 case "app.agenda":
993 openWindow(id: "agenda")
994 case "app.clock.in":
995 clockIn(.caret)
996 case "app.clock.in-recent":
997 clockIn(.select)
998 case "app.clock.in-last":
999 clockIn(.last)
1000 case let id where id.hasPrefix("app.clock.history."):
1001 if let index = Int(id.dropFirst("app.clock.history.".count)), index < clock.history.count { clockIn(.task(clock.history[index])) }
1002 case "app.clock.out":
1003 commands.show(clock.clockOut(session))
1004 case "app.clock.cancel":
1005 commands.show(clock.clockOut(session, cancel: true))
1006 case "app.clock.goto":
1007 let found = clock.goto(session)
1008 if let location = found.location { commands.jump(path: location.path, offset: location.offset) }
1009 if let message = found.message { commands.show(message) }
1010 case "app.clock.goto-recent":
1011 Task {
1012 let found = await clock.gotoRecent(session, ask: askClock)
1013 if let location = found.location { commands.jump(path: location.path, offset: location.offset) }
1014 if let message = found.message { commands.show(message) }
1015 }
1016 case "app.clock.default":
1017 commands.show(clock.markDefault(session))
1018 case "app.clock.resolve":
1019 Task { report(await clock.resolveOpenClocks(session, paths: orgFiles, ask: askClock)) }
1020 case "app.clock.report":
1021 openWindow(id: "clock-report")
1022 case "app.board":
1023 openWindow(id: "board")
1024 case "app.capture":
1025 NSApp.activate()
1026 openWindow(id: "capture")
1027 case "app.revert":
1028 // `:e`: the file as it is on disk; unsaved changes go to recovery.
1029 guard session.path != nil else { return commands.show("No file is open") }
1030 session.useDiskVersion()
1031 commands.show("Reverted to the file on disk")
1032 case "app.sync-conflicts":
1033 guard session.path != nil else { return commands.show("No file is open") }
1034 panel = .syncCopies(UUID())
1035 case "app.recovery":
1036 guard session.path != nil else { return commands.show("No file is open") }
1037 panel = .recovery(UUID())
1038 case "app.copy-rich-text":
1039 copyRichText()
1040 case "app.export-dialog":
1041 guard let path = session.path else { return commands.show("No file is open") }
1042 panel = .export(UUID(), URL(fileURLWithPath: path))
1043 case let id where id.hasPrefix("app.export."):
1044 export(String(id.dropFirst("app.export.".count)))
1045 case let id where id.hasPrefix("app.publish"):
1046 publish(id)
1047 case "app.plot":
1048 plotTable()
1049 default:
1050 if let editor = commands.editor { editor.run(id) } else { commands.show("No file is open") }
1051 }
1052 }
1053
1054 private var askClock: ClockModel.Ask { commands.askClock }
1055
1056 /// The files `org-resolve-clocks` looks through: the workspace's org files.
1057 private var orgFiles: [String] { workspace.files.filter { $0.kind == .org }.map(\.path) }
1058
1059 private func clockIn(_ target: ClockModel.Target) {
1060 Task { report(await clock.clockIn(session, target: target, paths: orgFiles, ask: askClock)) }
1061 }
1062
1063 /// The last message of a clock command, and the clock to show for `j`.
1064 private func report(_ outcome: ClockModel.Outcome) {
1065 if let jump = outcome.jump { commands.jump(path: jump.path, offset: jump.offset) }
1066 if let message = outcome.messages.last(where: { !$0.isEmpty }) { commands.show(message) }
1067 }
1068
1069 private var errorShown: Binding<Bool> {
1070 Binding(get: { workspace.lastError != nil || session.lastError != nil }, set: { _ in })
1071 }
1072}