Sources/Orgstar/ContentView.swift
1514 lines · 84562 bytes
1import AppKit
2import OrgApp
3import OrgCore
4import OrgEditorAppKit
5import OrgPresentation
6import OrgWorkspace
7import OrgIndex
8#if !APPSTORE
9import OrgPrograms
10#endif
11import SwiftUI
12import UniformTypeIdentifiers
13import WidgetKit
14
15struct ContentView: View {
16 let workspace: WorkspaceModel
17 let session: DocumentSession
18 @Bindable var commands: AppCommands
19 let scheduler: ReminderScheduler?
20 let clock: ClockModel
21 @AppStorage("reminders") private var remindersEnabled = true
22 @AppStorage("reminderLead") private var reminderLead = 12
23 @AppStorage("clockIdleTime") private var clockIdleTime = 0
24 @AppStorage("agendaSubfolders") private var agendaSubfolders = false
25 @State private var reminderAgenda: AgendaModel?
26 @State private var widgetAgenda: AgendaModel?
27 @State private var trust = TrustStore()
28 @State private var hotKey: GlobalHotKey?
29 @State private var statusItem: ClockStatusItem?
30 @AppStorage("globalCapture") private var globalCapture = true
31 @AppStorage("menuBarItem") private var menuBarItem = false
32 /// The sidebar shows the agenda in place of the files.
33 @AppStorage("sidebarAgenda") private var sidebarAgenda = false
34 /// Today's agenda for the menu bar item.
35 @State private var menuToday: [AgendaSnapshot.Row] = []
36 @State private var hour = 0
37 @AppStorage("saveMode") private var saveMode = SaveMode.automatic
38 @AppStorage("keymap") private var preset = KeymapPreset.emacs
39 @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
40 @State private var keymap = KeymapPreset.emacs.keymap
41 @AppStorage("tagsColumn") private var tagsColumn = -77
42 @AppStorage("headingAfterSubtree") private var headingAfterSubtree = false
43 /// The welcome sheet has been shown once; it comes back only through the empty state.
44 @AppStorage("welcomeShown") private var welcomeShown = false
45 @AppStorage("splitLine") private var splitLine = false
46 @AppStorage("alphabeticalLists") private var alphabeticalLists = true
47 @AppStorage("fillColumn") private var fillColumn = 80
48 @AppStorage("hiddenMarkers") private var hiddenMarkers = true
49 @AppStorage("prettyEntities") private var prettyEntities = true
50 @AppStorage("logDone") private var logDone = "nil"
51 @AppStorage("logIntoDrawer") private var logIntoDrawer = ""
52 @AppStorage("logReschedule") private var logReschedule = "nil"
53 @AppStorage("logRedeadline") private var logRedeadline = "nil"
54 @AppStorage("useSpeedCommands") private var useSpeedCommands = false
55 @AppStorage("startupWithInlineImages") private var startupWithInlineImages = false
56 @AppStorage("startupIndented") private var startupIndented = true
57 @AppStorage("hideLeadingStars") private var hideLeadingStars = false
58 @AppStorage("startupAlignAllTables") private var startupAlignAllTables = false
59 @AppStorage("startupTruncated") private var startupTruncated = false
60 @AppStorage("spellCheck") private var spellCheck = false
61 @AppStorage("electricPair") private var electricPair = true
62 @AppStorage("hideDrawerStartup") private var hideDrawerStartup = true
63 @AppStorage("hideBlockStartup") private var hideBlockStartup = false
64 @AppStorage("enforceTodoDependencies") private var enforceTodoDependencies = false
65 @AppStorage("enforceTodoCheckboxDependencies") private var enforceTodoCheckboxDependencies = false
66
67 /// Bumped when user defaults change, so settings only config.toml has reach `options`.
68 @State private var defaultsChanges = 0
69 private var options: EditingOptions {
70 _ = defaultsChanges
71 var options = Preferences.options(
72 tagsColumn: tagsColumn, headingAfterSubtree: headingAfterSubtree, splitLine: splitLine, alphabeticalLists: alphabeticalLists,
73 fillColumn: fillColumn, hiddenMarkers: hiddenMarkers, prettyEntities: prettyEntities, logDone: logDone, logIntoDrawer: logIntoDrawer,
74 hideDrawerStartup: hideDrawerStartup, hideBlockStartup: hideBlockStartup, logReschedule: logReschedule, logRedeadline: logRedeadline,
75 useSpeedCommands: useSpeedCommands, startupWithInlineImages: startupWithInlineImages,
76 startupIndented: startupIndented, hideLeadingStars: hideLeadingStars, startupAlignAllTables: startupAlignAllTables,
77 startupTruncated: startupTruncated, spellCheck: spellCheck, electricPair: electricPair,
78 enforceTodoDependencies: enforceTodoDependencies, enforceTodoCheckboxDependencies: enforceTodoCheckboxDependencies
79 )
80 // The agenda files, for clock tables over `agenda` scopes.
81 options.agendaFiles = workspace.agendaFilePaths()
82 options.denoteDirectories = DenoteNote.directories(roots: workspace.rootPaths)
83 options.denoteSequenceScheme = OrgPreferences.denoteSequenceScheme()
84 options.timer = TimerModel.shared.timer
85 return options
86 }
87 /// A block being edited apart (`org-edit-special`).
88 @State private var blockEdit: BlockEditRequest?
89 /// A sheet a command opened: column view or the export dialog.
90 @State private var panel: Panel?
91
92 @State private var selectedFile: String?
93 /// A file that isn't text, shown as a preview instead of the open document.
94 @State private var previewPath: String?
95 @AppStorage("outlineShown") private var orgOutlineShown = true
96 @AppStorage("outlineWidth") private var outlineWidth = 220.0
97 @AppStorage("backlinksShown") private var backlinksShown = true
98 @AppStorage("inspectorShown") private var inspectorShown = false
99 @AppStorage("showMarkup") private var showMarkup = false
100 @AppStorage("showLineNumbers") private var showLineNumbers = false
101 @AppStorage("lineNumbersType") private var lineNumbersType = "t"
102 @AppStorage("showHiddenFiles") private var showHiddenFiles = true
103 @AppStorage("ignoredFolders") private var ignoredFolders = ScanRules.defaultIgnoredFolders.sorted().joined(separator: " ")
104 @AppStorage("themeFont") private var themeFont = ""
105 @AppStorage("themeBodyFont") private var themeBodyFont = ""
106 @AppStorage("themeFontSize") private var themeFontSize = 13
107 @AppStorage("themeLineSpacing") private var themeLineSpacing = 2
108 @AppStorage("themeTextWidth") private var themeTextWidth = 0
109 @AppStorage("themeHeadingStep") private var themeHeadingStep = 1
110
111 /// The theme's colors from config.toml with the type settings.
112 private var theme: ThemeSpec {
113 var spec = ConfigSync.shared.theme
114 spec.font = themeFont
115 spec.bodyFont = themeBodyFont
116 spec.fontSize = themeFontSize
117 spec.lineSpacing = themeLineSpacing
118 spec.textWidth = themeTextWidth
119 spec.headingSizeStep = themeHeadingStep
120 return spec
121 }
122 /// The outline for a file that isn't org, off until asked for.
123 @State private var plainOutlineShown = false
124 @State private var showingImport = false
125 @AppStorage("showTabBar") private var showTabBar = false
126 /// This window's panes.
127 @State private var window: WindowModel?
128
129 private var editorSettings: EditorSettings {
130 EditorSettings(keymap: keymap, modal: preset.isModal, optionAsMeta: OptionAsMeta(rawValue: optionAsMeta), options: options, showMarkup: showMarkup, showLineNumbers: showLineNumbers,
131 lineNumbersType: LineNumbersType(rawValue: lineNumbersType) ?? .absolute, theme: theme)
132 }
133
134 /// The pane that had the focus when a sheet opened, to act on when it closes.
135 @State private var sheetTarget: EditorPane?
136
137 /// Puts the focus back on the pane a sheet was opened from.
138 private func restoreSheetTarget() {
139 guard let target = sheetTarget, session.panes.contains(where: { $0 === target }) else { return }
140 sheetTarget = nil
141 session.focused = target
142 if let window = commands.store.window(of: target.id) { window.focused = target.id }
143 if let path = target.path, let textView = commands.store.textView(for: target.id, path: path) {
144 textView.window?.makeFirstResponder(textView)
145 commands.editor = commands.store.editor(for: path)
146 }
147 }
148
149 /// The window holding the focused pane: this one, or an editor window.
150 private var paneWindow: WindowModel? {
151 commands.store.window(of: session.focused.id) ?? window
152 }
153
154 /// Gives the focused pane's text view the keyboard, after a pane command moved the focus.
155 private func focusPane(_ window: WindowModel) {
156 window.activate(commands)
157 }
158 /// Carets of restored buffers, shown when each first shows.
159 @State private var pendingCarets: [String: Int] = [:]
160 @State private var query = ""
161 @FocusState private var searchFocused: Bool
162 @Environment(\.openWindow) private var openWindow
163 @Environment(\.openSettings) private var openSettings
164
165 /// Whether the outline pane shows: remembered for org files, hidden by default for
166 /// other files, and always shown while search results are up.
167 private var outlineShown: Bool {
168 !query.isEmpty || (previewPath == nil && (session.isOrg ? orgOutlineShown : plainOutlineShown))
169 }
170
171 private func toggleOutline() {
172 if session.isOrg { orgOutlineShown.toggle() } else { plainOutlineShown.toggle() }
173 }
174
175 @ViewBuilder
176 private var detail: some View {
177 if let previewPath {
178 FilePreview(path: previewPath)
179 } else if !session.openPaths.isEmpty, let window {
180 PaneLayoutView(layout: window.layout, window: window) { pane in
181 PaneCell(pane: pane, window: window, session: session, commands: commands, showTabBar: showTabBar, onAppCommand: perform)
182 }
183 .safeAreaInset(edge: .bottom, spacing: 0) {
184 VStack(spacing: 0) {
185 ModeLine(session: session, commands: commands, clock: clock, perform: perform)
186 EchoArea(commands: commands)
187 }
188 }
189 } else {
190 ContentUnavailableView {
191 Label(noFolders ? "Add a folder of org files" : "Choose a file", systemImage: "doc.text")
192 } description: {
193 Text(noFolders ? "File ▸ Add Folder… (⇧⌘O)" : "Or press ⌘P to open one by name.")
194 } actions: {
195 if noFolders { Button("Get Started…") { commands.showingWelcome = true } }
196 }
197 }
198 }
199
200 /// No folder to show: in the App Store build, also when none of them resolves, so the
201 /// welcome sheet can ask for them again.
202 private var noFolders: Bool {
203 #if APPSTORE
204 workspace.rootPaths.isEmpty
205 #else
206 workspace.roots.isEmpty
207 #endif
208 }
209
210 /// The toolbar, which View ▸ Customize Toolbar… can change.
211 @ToolbarContentBuilder
212 private var toolbarItems: some CustomizableToolbarContent {
213 ToolbarItem(id: "outline", placement: .navigation) {
214 Button(outlineShown ? "Hide Outline" : "Show Outline", systemImage: "list.bullet.indent") { toggleOutline() }
215 .help(outlineShown ? "Hide the outline (⌥⌘O)" : "Show the outline (⌥⌘O)")
216 .disabled(!query.isEmpty || previewPath != nil || session.path == nil)
217 }
218 ToolbarItem(id: "capture") {
219 Button("Capture", systemImage: "square.and.pencil") { perform("app.capture") }
220 .help("Capture a note (⇧⌘N)")
221 }
222 ToolbarItem(id: "agenda") {
223 Button("Agenda", systemImage: "calendar") { perform("app.agenda") }
224 .help("Open the agenda (⇧⌘A)")
225 }
226 ToolbarItem(id: "commands") {
227 Button("Commands", systemImage: "command") { commands.showingPalette = true }
228 .help("Find a command by name (⇧⌘P)")
229 }
230 ToolbarItem(id: "inspector") {
231 Button(inspectorShown ? "Hide Columns and Clock" : "Show Columns and Clock", systemImage: "sidebar.trailing") { inspectorShown.toggle() }
232 .help(inspectorShown ? "Hide the columns and clocked time (⌥⌘I)" : "Show the columns and clocked time (⌥⌘I)")
233 }
234 if workspace.isIndexing {
235 ToolbarItem(id: "indexing") { ProgressView().controlSize(.small) }
236 .customizationBehavior(.disabled)
237 }
238 if let running = clock.running {
239 ToolbarItem(id: "clock") {
240 Menu {
241 Button("Clock Out") { perform("app.clock.out") }
242 Button("Cancel Clock") { perform("app.clock.cancel") }
243 Button("Go to Clocked Entry") { perform("app.clock.goto") }
244 Divider()
245 Button("Clock In to Recent Entry…") { perform("app.clock.in-recent") }
246 Button("Go to Recent Clocked Entry…") { perform("app.clock.goto-recent") }
247 RecentClocks(clock: clock) { perform($0) }
248 } label: {
249 TimelineView(.periodic(from: .now, by: 30)) { context in
250 Text("⏱ \(running.heading) \(clockElapsed(running, now: context.date))").lineLimit(1)
251 }
252 }
253 .help("Clocked in since \(running.startedAt.formatted(date: .omitted, time: .shortened))")
254 }
255 }
256 if session.conflict != nil {
257 ToolbarItem(id: "conflict") {
258 Button("Conflict", systemImage: "exclamationmark.triangle") { commands.showingConflict = true }
259 .help("The file changed on disk, and the changes conflict with yours")
260 }
261 .customizationBehavior(.disabled)
262 }
263 }
264
265 private var main: some View {
266 NavigationSplitView {
267 Group {
268 if sidebarAgenda {
269 AgendaSidebar(workspace: workspace, session: session, commands: commands, hour: hour, showsAgenda: $sidebarAgenda)
270 } else {
271 Sidebar(workspace: workspace, session: session, selection: $selectedFile, showsAgenda: $sidebarAgenda) { commands.showingFolderPicker = true }
272 }
273 }
274 .navigationSplitViewColumnWidth(min: 200, ideal: 260)
275 } detail: {
276 HStack(spacing: 0) {
277 if outlineShown {
278 Group {
279 if query.isEmpty {
280 VStack(spacing: 0) {
281 OutlineColumn(session: session)
282 if backlinksShown, session.isOrg {
283 Divider()
284 BacklinksPane(workspace: workspace, session: session, commands: commands) { location in
285 selectedFile = location.path
286 session.show(location)
287 }
288 .frame(height: 200)
289 }
290 }
291 } else {
292 SearchResults(results: Result { try workspace.search(query, overlay: workspace.overlay(session.openDocuments)) }) { location in
293 selectedFile = location.path
294 session.show(location)
295 }
296 }
297 }
298 .frame(width: CGFloat(outlineWidth))
299 PaneDivider(width: $outlineWidth, range: 160...400)
300 }
301 detail
302 .frame(maxWidth: .infinity)
303 .inspector(isPresented: $inspectorShown) {
304 InspectorPane(session: session, commands: commands, shown: inspectorShown)
305 .inspectorColumnWidth(min: 240, ideal: 340, max: 600)
306 }
307 }
308 }
309 .navigationTitle(previewPath.map { ($0 as NSString).lastPathComponent } ?? session.path.map(session.bufferName) ?? "orgstar")
310 .navigationSubtitle(session.isReadOnly ? "Read-only: not UTF-8" : "")
311 .searchable(text: $query, placement: .toolbar, prompt: "Search notes")
312 .searchFocused($searchFocused)
313 .toolbar(id: "main") { toolbarItems }
314 .onChange(of: session.path) { plainOutlineShown = false }
315 .onChange(of: ScanRules(hiddenFiles: showHiddenFiles, ignoredFolders: Set(ignoredFolders.split(separator: " ").map(String.init))), initial: true) { _, rules in
316 workspace.scanRules = rules
317 }
318 .onChange(of: selectedFile) { old, path in
319 guard let path else { return }
320 if !DocumentSession.isOrgPath(path), !FileTypes.isText(path) {
321 previewPath = path
322 return
323 }
324 previewPath = nil
325 guard path != session.path else { return }
326 session.open(path)
327 }
328 .onChange(of: session.path) {
329 // Buffers switched by keys show in the sidebar too; a restored caret shows once.
330 if let path = session.path, selectedFile != path { selectedFile = path }
331 if let path = session.path, let caret = pendingCarets.removeValue(forKey: path) { session.reveal(caret) }
332 saveBuffers()
333 // Syncthing's conflict copies of the file.
334 let copies = session.syncConflictCopies().count
335 if copies > 0 { commands.show("\(copies) sync conflict \(copies == 1 ? "copy" : "copies") of this file; Resolve Sync Conflicts compares them.") }
336 }
337 .onChange(of: session.openPaths) { _, paths in
338 saveBuffers()
339 for path in commands.store.editors.keys where !paths.contains(path) { commands.store.releasePath(path) }
340 }
341 .onChange(of: editorSettings, initial: true) { _, settings in commands.editorSettings = settings }
342 .onAppear {
343 commands.externalHandler = runExternal
344 commands.filesHandler = { attachActions.drop($0) }
345 commands.imageHandler = { attachActions.yankImage($0, ext: $1) }
346 #if APPSTORE
347 commands.reach = { [workspace] in GrantAccess.reach($0, workspace: workspace) }
348 #endif
349 // `org-clock-out-when-done`, and the notification when the Effort runs out.
350 clock.notifications = SystemReminderCenter.isAvailable ? SystemReminderCenter() : nil
351 session.textChanged = { [weak session, weak clock, weak commands] path in
352 guard let session, let clock, let message = clock.textChanged(path, session) else { return }
353 commands?.show(message)
354 }
355 clock.remindAtEffort(session)
356 commands.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] }
357 commands.mainWindowOpen = true
358 commands.whatsNew = WhatsNew.pending(firstLaunch: noFolders && !welcomeShown)
359 if noFolders, !welcomeShown {
360 welcomeShown = true
361 commands.showingWelcome = true
362 }
363 if let stale = window { commands.store.windows.removeAll { $0 === stale } }
364 // The session's first pane the first time; a new one showing the focused buffer
365 // when the window opens again.
366 let pane: EditorPane
367 if commands.store.window(of: session.panes[0].id) == nil, window == nil {
368 pane = session.panes[0]
369 } else {
370 pane = session.makePane()
371 if let path = session.focused.path { session.open(path, in: pane) }
372 }
373 let model = WindowModel(session: session, pane: pane)
374 window = model
375 commands.store.windows.insert(model, at: 0)
376 model.focus(pane.id)
377 }
378 .onDisappear {
379 commands.mainWindowOpen = false
380 guard let model = window else { return }
381 for id in model.layout.panes { commands.store.releasePane(id) }
382 model.closeAll()
383 commands.store.windows.removeAll { $0 === model }
384 commands.editor = nil
385 }
386 .onChange(of: saveMode, initial: true) { _, mode in session.saveMode = mode }
387 .onChange(of: options, initial: true) { _, options in session.options = options }
388 .onAppear { TimerModel.shared.onDone = { [commands] in commands.show($0) } }
389 .onReceive(NotificationCenter.default.publisher(for: UserDefaults.didChangeNotification)) { _ in defaultsChanges += 1 }
390 .onChange(of: preset, initial: true) { loadKeymap() }
391 .sheet(isPresented: $showingImport) { EmacsImportView(workspace: workspace) }
392 .sheet(item: $panel) { panel in panelView(panel) }
393 .sheet(item: Bindable(ProAccess.shared).paywall) { feature in
394 #if APPSTORE
395 StorePaywallSheet(feature: feature)
396 #else
397 ProPaywallSheet(feature: feature)
398 #endif
399 }
400 .sheet(item: $blockEdit) { request in
401 BlockEditorView(edit: request.edit) { content in
402 blockEdit = nil
403 guard let content else { return }
404 commands.editor?.perform(ReplaceBlockLines(edit: request.edit, content: content))
405 }
406 }
407 .sheet(isPresented: $commands.showingWelcome) {
408 WelcomeView(workspace: workspace, chooseFolder: {
409 // After the sheet closes, so the picker can present.
410 DispatchQueue.main.async { commands.showingFolderPicker = true }
411 }, open: { selectedFile = $0 })
412 }
413 .sheet(item: $commands.whatsNew) { WhatsNewView(notes: $0) }
414 .sheet(isPresented: $commands.showingPalette) {
415 PaletteView(commands: commands) { id in
416 commands.showingPalette = false
417 // After the sheet closes, so app commands can present their own, and in the
418 // pane that had the focus when it opened: closing a sheet makes this window key.
419 DispatchQueue.main.async {
420 restoreSheetTarget()
421 perform(id)
422 }
423 }
424 }
425 .sheet(isPresented: $commands.showingMessages) { MessagesView(messages: commands.messages) }
426 .onChange(of: commands.showingPalette) { _, showing in if showing { sheetTarget = session.focused } }
427 .onChange(of: commands.showingQuickOpen) { _, showing in if showing { sheetTarget = session.focused } }
428 .onChange(of: session.conflict) { _, conflict in
429 if conflict != nil { commands.showingConflict = true }
430 }
431 .onChange(of: commands.showingConflict) { _, showing in
432 guard showing else { return }
433 commands.showingConflict = false
434 if session.conflict != nil { panel = .conflict(UUID()) }
435 }
436 .onChange(of: workspace.changedFile?.version) { fileChangedOnDisk() }
437 }
438
439 /// A column view edit at the heading starting at `start` in the open file.
440 private func runInColumnView(_ command: any OrgCommand, _ start: Int, _ answers: [String: String]) -> CommandStep {
441 guard let path = session.path else { return .failed("No file is open") }
442 return session.perform(command, path: path, at: start, expect: nil, answers: answers)
443 }
444
445 /// An open file takes in what changed on disk, and a clock started or stopped in Emacs
446 /// becomes the one shown.
447 private func fileChangedOnDisk() {
448 guard let path = workspace.changedFile?.path else { return }
449 session.fileChanged(path)
450 if path.hasSuffix(".org") { syncClock(paths: [path]) }
451 }
452
453 /// Open clocks in `paths`: at launch and as folders load, the agenda files.
454 private func syncClock(paths: [String]) {
455 guard !workspace.files.isEmpty, let message = clock.sync(session, paths: paths) else { return }
456 commands.show(message)
457 }
458
459 var body: some View {
460 main
461 .task(id: workspace.files.count) { syncClock(paths: workspace.agendaFilePaths()) }
462 .onChange(of: ClockMenuState(running: clock.running, history: clock.history, always: menuBarItem, today: menuToday), initial: true) { _, state in
463 if statusItem == nil { statusItem = ClockStatusItem(run: { commands.run($0) }, jump: { commands.jump(path: $0, offset: $1) }) }
464 statusItem?.update(state)
465 }
466 .task(id: menuBarItem) { if menuBarItem { await updateWidgets() } }
467 .onChange(of: globalCapture, initial: true) { _, enabled in
468 hotKey?.unregister()
469 hotKey = enabled ? GlobalHotKey { perform("app.capture") } : nil
470 }
471 .onChange(of: commands.runRequest?.serial, initial: true) {
472 if let id = commands.runRequest?.id { perform(id) }
473 }
474 .onChange(of: ConfigSync.shared.problems, initial: true) { _, problems in
475 if let first = problems.first {
476 commands.show(first + (problems.count > 1 ? " (and \(problems.count - 1) more)" : ""))
477 }
478 }
479 .onChange(of: ConfigSync.shared.changedFile?.serial) {
480 if ConfigSync.shared.changedFile?.name == "keymap.toml" { loadKeymap() }
481 }
482 .onChange(of: commands.jumpRequest?.id) {
483 guard let request = commands.jumpRequest else { return }
484 if request.path != session.path {
485 session.open(request.path)
486 selectedFile = request.path
487 }
488 session.reveal(request.offset)
489 }
490 .onChange(of: commands.focusSearch) { _, focus in
491 if focus {
492 searchFocused = true
493 commands.focusSearch = false
494 }
495 }
496 .fileImporter(isPresented: $commands.showingFolderPicker, allowedContentTypes: [.folder]) { result in
497 guard case .success(let url) = result else { return }
498 Task {
499 do { try await workspace.addRoot(url) } catch { workspace.lastError = error.localizedDescription }
500 }
501 }
502 .sheet(isPresented: $commands.showingQuickOpen) {
503 QuickOpenView(workspace: workspace) { entry in
504 commands.showingQuickOpen = false
505 DispatchQueue.main.async {
506 restoreSheetTarget()
507 selectedFile = entry.path
508 if selectedFile == entry.path { session.open(entry.path) }
509 }
510 }
511 }
512 .alert("orgstar", isPresented: errorShown) {
513 Button("OK") {
514 workspace.lastError = nil
515 session.lastError = nil
516 }
517 } message: {
518 Text(workspace.lastError ?? session.lastError ?? "")
519 }
520 .task(id: ReminderKey(
521 enabled: remindersEnabled, lead: reminderLead, subfolders: agendaSubfolders, hidden: HiddenFolders.shared.all, files: workspace.files.count,
522 changed: workspace.changedFile?.version, edits: session.editVersion, hour: hour, theme: theme
523 )) {
524 // Once edits pause.
525 try? await Task.sleep(for: .seconds(2))
526 await updateReminders()
527 await updateWidgets()
528 }
529 .task {
530 while !Task.isCancelled {
531 try? await Task.sleep(for: .seconds(3600))
532 hour += 1
533 }
534 }
535 // `org-resolve-clocks-if-idle`, checked every minute while a clock runs.
536 .task(id: "\(clock.running?.start ?? "") \(clockIdleTime)") {
537 guard clock.running != nil, clockIdleTime > 0 else { return }
538 while !Task.isCancelled {
539 try? await Task.sleep(for: .seconds(60))
540 guard !Task.isCancelled, clock.running != nil, !clock.isResolving else { continue }
541 let idle = ClockIdle.seconds()
542 guard idle > Double(clockIdleTime * 60) else { continue }
543 NSApp.requestUserAttention(.informationalRequest)
544 report(await clock.resolveIdle(session, idleSince: Date().addingTimeInterval(-idle), ask: askClock))
545 }
546 }
547 .task {
548 #if !APPSTORE
549 DevelopmentHooks.scheduleSnapshot()
550 #endif
551 pendingCarets = BufferRestore.restore(session)
552 if let path = session.path, let caret = pendingCarets.removeValue(forKey: path) { session.reveal(caret) }
553 // Files handed over at launch open after the restored buffers, and show.
554 for path in AppDelegate.pendingOpens { session.open(path) }
555 AppDelegate.pendingOpens = []
556 #if APPSTORE
557 for link in AppDelegate.pendingLinks { commands.handle(protocolURL: link) }
558 AppDelegate.pendingLinks = []
559 #else
560 for link in AppDelegate.pendingLinks + [DevelopmentHooks.urlToOpen].compactMap({ $0 }) { commands.handle(protocolURL: link) }
561 AppDelegate.pendingLinks = []
562 if let path = DevelopmentHooks.fileToOpen { selectedFile = path }
563 if let root = DevelopmentHooks.rootToAdd { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
564 if let commandList = DevelopmentHooks.commandToRun {
565 // The file opened above needs its editor first.
566 for _ in 0..<20 where DevelopmentHooks.fileToOpen != nil && commands.editor == nil { try? await Task.sleep(for: .milliseconds(100)) }
567 for command in commandList.split(separator: ",") { perform(String(command)) }
568 for answer in DevelopmentHooks.answers {
569 for _ in 0..<20 where commands.prompt == nil { try? await Task.sleep(for: .milliseconds(100)) }
570 commands.answer(answer)
571 }
572 }
573 if let id = DevelopmentHooks.windowToOpen {
574 if id == "settings" { openSettings() } else { openWindow(id: id) }
575 }
576 #endif
577 await workspace.refresh()
578 workspace.startWatching()
579 }
580 }
581
582 /// The selection, or the whole file without one, on the clipboard as HTML, RTF and plain
583 /// text, to paste formatted into mail and documents.
584 private func copyRichText() {
585 guard let path = session.path, let whole = session.document?.text, let editor = commands.editor else { return commands.show("No file is open") }
586 let defaults = Preferences.orgSettings.resolvingSetupFiles(in: whole, path: path, read: OrgSettings.readFile)
587 let selection = editor.context().selection.first { !$0.isEmpty }
588 let selected = selection.map { (whole as NSString).substring(with: NSRange($0)) }
589 let url = URL(fileURLWithPath: path)
590 let html = HTMLExport.page(
591 selected ?? whole, fallbackTitle: url.deletingPathExtension().lastPathComponent, settings: defaults, path: path, bodyOnly: selected != nil,
592 codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme), language: OrgPreferences.exportLanguage()
593 )
594 do {
595 try RichTextExport.copy(html: html, directory: url.deletingLastPathComponent())
596 commands.show(selected == nil ? "Copied the file as rich text" : "Copied the selection as rich text")
597 } catch {
598 commands.show("\(error)")
599 }
600 }
601
602 /// Whether the caret is in a heading's subtree, which the export dialog can export alone.
603 private var exportSubtreeAvailable: Bool {
604 guard let text = session.document?.text, let caret = commands.editor?.context().caret else { return false }
605 return ExportScope.subtree(text, at: caret) != nil
606 }
607
608 /// Where an export goes by default: `#+EXPORT_FILE_NAME`, or the subtree's
609 /// `EXPORT_FILE_NAME`, else beside the file, with `ext`.
610 private func exportTarget(_ ext: String, subtree: Bool) -> URL {
611 let path = session.path ?? ""
612 let text = session.document?.text ?? ""
613 let caret = subtree ? commands.editor?.context().caret : nil
614 return ExportScope.output(for: URL(fileURLWithPath: path), name: ExportScope.fileName(text, subtreeAt: caret), extension: ext)
615 }
616
617 /// Writes the export where `#+EXPORT_FILE_NAME` says or beside the file, as Emacs's export
618 /// dispatcher does, or to `destination`, and opens it with `open`. `subtree` exports the
619 /// subtree at the caret alone; `bodyOnly` leaves out the title and page wrapper.
620 private func export(_ format: String, to destination: URL? = nil, open: Bool = false, subtree: Bool = false, bodyOnly: Bool = false) {
621 if let feature = ProFeature.required(byExport: format), !ProAccess.shared.allows(feature) { return }
622 if format == "icalendar-agenda" || format == "icalendar-combined" { return exportAgendaCalendars(combined: format == "icalendar-combined") }
623 guard let path = session.path, var text = session.document?.text else {
624 commands.show("No file is open")
625 return
626 }
627 guard readsIncludes(text, path: path) else { return }
628 let url = URL(fileURLWithPath: path)
629 let base = url.deletingPathExtension()
630 let defaults = Preferences.orgSettings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
631 let open = open || format == "html-open"
632 let caret = commands.editor?.context().caret ?? 0
633 let whole = text
634 if subtree {
635 guard let narrowed = ExportScope.subtree(text, at: caret, settings: defaults) else { return commands.show("Not in a subtree") }
636 text = narrowed
637 }
638 switch format {
639 case "icalendar":
640 let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
641 guard let destination = destination ?? writable(ExportScope.output(for: url, name: name, extension: "ics")) else { return }
642 do {
643 let target = try ICalendarFiles.export(whole, path: path, settings: defaults, options: OrgPreferences.icalendarOptions(),
644 subtree: subtree ? caret : nil, destination: destination)
645 commands.show(ExportSettings.exported(target.lastPathComponent, subtree: subtree, bodyOnly: bodyOnly))
646 if open { NSWorkspace.shared.open(target) }
647 } catch {
648 commands.show("Can't export: \(error.localizedDescription)")
649 }
650 case "html", "html-open", "markdown":
651 let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
652 guard let target = destination ?? writable(ExportScope.output(for: url, name: name, extension: format == "markdown" ? "md" : "html")) else { return }
653 let content = format == "markdown"
654 ? MarkdownExport.document(text, settings: defaults, path: path, bodyOnly: bodyOnly)
655 : HTMLExport.page(
656 text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path, bodyOnly: bodyOnly,
657 codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme), language: OrgPreferences.exportLanguage()
658 )
659 do {
660 try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
661 try content.write(to: target, atomically: true, encoding: .utf8)
662 commands.show(ExportSettings.exported(target.lastPathComponent, subtree: subtree, bodyOnly: bodyOnly))
663 if open { NSWorkspace.shared.open(target) }
664 } catch {
665 commands.show("Can't write \(target.lastPathComponent): \(error.localizedDescription)")
666 }
667 case "latex" where exportNative("LaTeX", extension: "tex", whole: whole, url: url, to: destination, open: open, subtree: subtree ? caret : nil, bodyOnly: bodyOnly, settings: defaults, export: {
668 try LaTeXExport.document(text, settings: defaults, path: path, bodyOnly: bodyOnly, author: NSFullUserName(), language: OrgPreferences.exportLanguage(), file: true)
669 }):
670 break
671 case "text" where exportNative("plain text", extension: "txt", whole: whole, url: url, to: destination, open: open, subtree: subtree ? caret : nil, bodyOnly: bodyOnly, settings: defaults, export: {
672 try ASCIIExport.document(text, settings: defaults, path: path, bodyOnly: bodyOnly, author: NSFullUserName(), language: OrgPreferences.exportLanguage(), file: true)
673 }):
674 break
675 case "odt":
676 let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
677 guard let target = destination ?? writable(ExportScope.output(for: url, name: name, extension: "odt")) else { return }
678 // A missing image stops the export, so offer access to them first.
679 _ = reach(ODTExport.imageFiles(text, settings: defaults, path: path).filter(WorkspaceModel.isThere))
680 do {
681 let data = try ODTExport.document(text, settings: defaults, path: path, author: NSFullUserName(), language: OrgPreferences.exportLanguage())
682 try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
683 try data.write(to: target, options: .atomic)
684 commands.show(ExportSettings.exported(target.lastPathComponent, subtree: subtree, bodyOnly: bodyOnly))
685 if open { NSWorkspace.shared.open(target) }
686 } catch {
687 commands.show("Can't export \(target.lastPathComponent): \(error.localizedDescription)")
688 }
689 case "print-pdf", "docx", "rtf", "plain-text":
690 let ext = ["print-pdf": "pdf", "plain-text": "txt"][format] ?? format
691 let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
692 guard let target = destination ?? writable(ExportScope.output(for: url, name: name, extension: ext)) else { return }
693 let html = HTMLExport.page(
694 text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path,
695 codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme), language: OrgPreferences.exportLanguage()
696 )
697 let directory = url.deletingLastPathComponent()
698 // Images that can't be read are left out, so offer access to them first.
699 _ = reach(PDFExport.imageFiles(html, directory: directory).filter(WorkspaceModel.isThere))
700 if format == "print-pdf" { commands.show("Exporting to PDF…") }
701 Task {
702 do {
703 let data: Data
704 switch format {
705 case "print-pdf": data = try await PDFExport.pdf(html: html, directory: directory, options: OrgPreferences.pdfOptions())
706 case "docx": data = try RichTextExport.docx(html: html, directory: directory)
707 case "rtf": data = try RichTextExport.rtf(RichTextExport.attributed(html: html, directory: directory))
708 default: data = Data(RichTextExport.plain(try RichTextExport.attributed(html: html, directory: directory)).utf8)
709 }
710 try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
711 try data.write(to: target, options: .atomic)
712 commands.show(ExportSettings.exported(target.lastPathComponent, subtree: subtree, bodyOnly: bodyOnly))
713 if open { NSWorkspace.shared.open(target) }
714 } catch {
715 commands.show("Can't export \(target.lastPathComponent): \(error)")
716 }
717 }
718 default:
719 #if !APPSTORE
720 let functions = ["pdf": "org-latex-export-to-pdf", "latex": "org-latex-export-to-latex", "text": "org-ascii-export-to-ascii"]
721 guard let function = functions[format] else { return }
722 commands.show("Exporting with Emacs…")
723 commands.runInEmacs {
724 do {
725 // Emacs narrows to the subtree and reads EXPORT_FILE_NAME itself.
726 let point = subtree ? (whole as NSString).substring(to: min(caret, (whole as NSString).length)).unicodeScalars.count + 1 : nil
727 var written = URL(fileURLWithPath: try await EmacsRunner.export(
728 text: whole, path: path, function: function, subtree: point, bodyOnly: bodyOnly
729 ))
730 if let destination, destination.standardizedFileURL != written.standardizedFileURL {
731 try? FileManager.default.removeItem(at: destination)
732 try FileManager.default.moveItem(at: written, to: destination)
733 written = destination
734 }
735 commands.show(ExportSettings.exported(written.lastPathComponent, subtree: subtree, bodyOnly: bodyOnly))
736 if open { NSWorkspace.shared.open(written) }
737 } catch is CancellationError {
738 commands.show("Export canceled")
739 } catch {
740 commands.show("\(error)")
741 }
742 }
743 #else
744 let title = EditorCommands.all.first { $0.id == "app.export." + format }?.title
745 commands.show(Self.unavailable(title ?? format))
746 #endif
747 }
748 }
749
750 /// Writes what `export` makes, as ox does for `format`. False when the native export can't
751 /// match Emacs and Emacs is installed to export instead; otherwise the reason is shown.
752 private func exportNative(
753 _ format: String, extension ext: String, whole: String, url: URL, to destination: URL?, open: Bool, subtree: Int?, bodyOnly: Bool, settings: OrgSettings,
754 export: () throws -> String
755 ) -> Bool {
756 let content: String
757 do {
758 content = try export()
759 } catch {
760 #if !APPSTORE
761 if EmacsRunner.executable() != nil { return false }
762 #endif
763 commands.show("Can't export to \(format): \(error.localizedDescription)")
764 return true
765 }
766 let name = ExportScope.fileName(whole, subtreeAt: subtree, settings: settings)
767 guard let target = destination ?? writable(ExportScope.output(for: url, name: name, extension: ext)) else { return true }
768 do {
769 try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
770 try content.write(to: target, atomically: true, encoding: .utf8)
771 commands.show(ExportSettings.exported(target.lastPathComponent, subtree: subtree != nil, bodyOnly: bodyOnly))
772 if open { NSWorkspace.shared.open(target) }
773 } catch {
774 commands.show("Can't write \(target.lastPathComponent): \(error.localizedDescription)")
775 }
776 return true
777 }
778
779 /// `url`; in the App Store build, when the sandbox keeps orgstar out of its folder, `url` once
780 /// that folder is granted, or where a save panel puts it instead. Nil when canceled.
781 private func writable(_ url: URL) -> URL? {
782 #if APPSTORE
783 guard let folder = workspace.foldersToGrant(for: [url.path]).first else { return url }
784 let elsewhere = String(localized: "Save Elsewhere…", comment: "Button that asks where an export goes instead")
785 switch GrantAccess.ask(folder, workspace: workspace, alternative: elsewhere) {
786 case .granted: return url
787 case .canceled: return nil
788 case .alternative: break
789 }
790 let panel = NSSavePanel()
791 panel.directoryURL = url.deletingLastPathComponent()
792 panel.nameFieldStringValue = url.lastPathComponent
793 panel.message = String(localized: "This file isn't in one of your folders. Choose where the export goes.", comment: "Save panel for an export outside the sidebar's folders")
794 return panel.runModal() == .OK ? panel.url : nil
795 #else
796 return url
797 #endif
798 }
799
800 private func saveBuffers() {
801 #if APPSTORE
802 BufferRestore.save(session, workspace: workspace)
803 #else
804 BufferRestore.save(session)
805 #endif
806 }
807
808 /// In the App Store build, asks for the folders outside the sidebar's folders that `paths`
809 /// need. False when one is still out of reach.
810 private func reach(_ paths: @autoclosure () -> [String], directories: Bool = false) -> Bool {
811 #if APPSTORE
812 GrantAccess.reach(paths(), directories: directories, workspace: workspace)
813 #else
814 true
815 #endif
816 }
817
818 /// In the App Store build, offers access to the setup files and includes of `text` that
819 /// can't be read. False, with a message, when an include still can't be read, rather than
820 /// exporting it as an empty line.
821 private func readsIncludes(_ text: String, path: String) -> Bool {
822 #if APPSTORE
823 let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
824 var setupFiles: [String] = []
825 _ = Preferences.orgSettings.resolvingSetupFiles(in: text, path: path) { file in
826 let contents = OrgSettings.readFile(file)
827 if contents == nil, WorkspaceModel.isThere(file) { setupFiles.append(file) }
828 return contents
829 }
830 let includes = ExportPreprocess.unreadableIncludes(text, directory: directory).filter(WorkspaceModel.isThere)
831 guard !(setupFiles + includes).isEmpty else { return true }
832 _ = reach(setupFiles + includes)
833 guard let unreadable = ExportPreprocess.unreadableIncludes(text, directory: directory).first else { return true }
834 commands.show(String(localized: "Can't include \(OrgPaths.abbreviatingWithTilde(unreadable)).", comment: "Export stopped by an #+INCLUDE file that can't be read"))
835 return false
836 #else
837 return true
838 #endif
839 }
840
841 /// Says a command doesn't run in this build.
842 static func unavailable(_ title: String) -> String {
843 String(localized: "\(CommandTitle.localized(title)) isn't available.", comment: "A command the Mac App Store build leaves out")
844 }
845
846 /// `org-icalendar-export-agenda-files`, or with `combined`, `org-icalendar-combine-agenda-files`.
847 private func exportAgendaCalendars(combined: Bool) {
848 let paths = workspace.agendaFilePaths()
849 guard reach(paths + (combined ? [OrgPreferences.icalendarCombinedFile()] : [])) else { return }
850 let read = { (path: String) -> (text: String, settings: OrgSettings)? in
851 guard let text = session.openDocuments.first(where: { $0.path == path })?.document.text ?? (try? String(contentsOfFile: path, encoding: .utf8)) else { return nil }
852 return (text, Preferences.orgSettings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile))
853 }
854 do {
855 let options = OrgPreferences.icalendarOptions()
856 if combined {
857 let url = try ICalendarFiles.combine(paths, to: OrgPreferences.icalendarCombinedFile(), options: options, read: read)
858 commands.show("Exported \(paths.count) agenda files to \(url.lastPathComponent)")
859 } else {
860 let written = try ICalendarFiles.exportEach(paths, options: options, read: read)
861 commands.show("Exported \(written.count) agenda files to iCalendar")
862 }
863 } catch {
864 commands.show("Can't export: \(error.localizedDescription)")
865 }
866 }
867
868 /// org-crypt's commands at the caret, through the passphrase sheet.
869 private func crypt(_ id: String) {
870 guard let editor = commands.editor, let path = session.path else { return commands.show("No file is open") }
871 let caret = editor.context().caret
872 let text = editor.context().text
873 switch id {
874 case "app.crypt.forget-passphrase":
875 CryptPassphrases.forget(path)
876 commands.show("Passphrase forgotten for \((path as NSString).lastPathComponent)")
877 case "app.crypt.encrypt-entries":
878 panel = .crypt(UUID(), CryptRequest(mode: .encryptAll(tag: OrgPreferences.cryptTag()), path: path, offset: caret))
879 default:
880 guard OrgCrypt.heading(text, at: caret) != nil else { return commands.show("Before first headline") }
881 if id == "app.crypt.encrypt-entry" {
882 guard OrgCrypt.encryptedRange(text, at: caret) == nil else { return commands.show("The entry is encrypted already") }
883 panel = .crypt(UUID(), CryptRequest(mode: .encrypt, path: path, offset: caret))
884 } else {
885 guard OrgCrypt.encryptedRange(text, at: caret) != nil else { return commands.show("Not an encrypted entry") }
886 panel = .crypt(UUID(), CryptRequest(mode: id == "app.crypt.open-entry" ? .open : .decryptInPlace, path: path, offset: caret))
887 }
888 }
889 }
890
891 /// org-roam's daily notes and nodes.
892 private var roamActions: RoamActions {
893 var actions = RoamActions(
894 session: session, roots: { [workspace] in workspace.rootPaths },
895 nodes: { [workspace, session] in try workspace.nodes(overlay: workspace.overlay(session.openDocuments)) },
896 show: { [commands] in commands.show($0) }, ask: { [commands] in commands.ask($0, reply: $1) },
897 open: { [commands] path, offset in commands.jump(path: path, offset: offset) },
898 insertLink: { [commands] link, title in
899 guard let editor = commands.editor else { return commands.show("No file is open") }
900 let context = editor.context()
901 let range = context.selection.first ?? context.caret..<context.caret
902 let selected = (context.text as NSString).substring(with: NSRange(range))
903 let text = Links.makeString(link, selected.isEmpty ? title : selected)
904 let end = range.lowerBound + (text as NSString).length
905 editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: [TextEdit(range: range, replacement: text)], selection: [end..<end])))
906 },
907 refresh: { [workspace] in Task { await workspace.refresh() } })
908 #if APPSTORE
909 actions.reachFolders = { [workspace] in GrantAccess.reach($0, directories: true, workspace: workspace) }
910 #endif
911 return actions
912 }
913
914 /// org-attach's commands for the entry at the caret.
915 private var attachActions: AttachActions {
916 AttachActions(
917 entry: { [commands, session] in
918 guard let editor = commands.editor, let path = session.path else { return nil }
919 let context = editor.context()
920 return Attachments.Entry(text: context.text, offset: context.caret, path: path, options: context.options)
921 },
922 apply: { applyText($0, caret: $1) }, show: { [commands] in commands.show($0) }, ask: { [commands] in commands.ask($0, reply: $1) },
923 storeLink: { [commands] in _ = StoredLink.add($0, to: &commands.storedLinks) },
924 open: { [session, workspace, commands] file in
925 if let message = LinkOpener.open(OrgLink(type: "file", path: file, raw: "file:" + file), session: session, workspace: workspace, ask: commands.ask) { commands.show(message) }
926 },
927 reveal: { NSWorkspace.shared.open(URL(fileURLWithPath: $0, isDirectory: true)) },
928 pick: { method in
929 let panel = NSOpenPanel()
930 panel.canChooseDirectories = true
931 panel.allowsMultipleSelection = true
932 panel.message = "File to keep as an attachment"
933 guard panel.runModal() == .OK else { return }
934 #if APPSTORE
935 // The sandbox can remove only files in the sidebar's folders, and links nothing.
936 if method == .mv, let outside = panel.urls.first(where: { !workspace.contains($0) }) {
937 return commands.show(String(localized: "\(outside.lastPathComponent) isn't in one of your folders, so it can't be moved. Attach a copy instead.", comment: "Attach by moving a file from outside the sidebar's folders"))
938 }
939 guard method == .cp || method == .mv else { return }
940 #endif
941 attachActions.attach(panel.urls, method: method)
942 })
943 }
944
945 /// The sheet a panel shows.
946 @ViewBuilder
947 private func panelView(_ panel: Panel) -> some View {
948 switch panel {
949 case .columns(_, let view):
950 ColumnViewSheet(view: view, run: runInColumnView, document: { session.document.map { ($0.text, $0.tree) } }) { offset in
951 commands.editor?.reveal(offset)
952 }
953 case .export(_, let source):
954 ExportSheet(source: source, inSubtree: exportSubtreeAvailable, target: exportTarget) { format, destination, open, subtree, bodyOnly in
955 export(format, to: destination, open: open, subtree: subtree, bodyOnly: bodyOnly)
956 }
957 case .plot(_, let plot):
958 PlotSheet(content: .chart(plot))
959 case .plotImage(_, let url):
960 PlotSheet(content: .image(url))
961 case .crypt(_, let request):
962 CryptSheet(request: request, text: { session.document?.text ?? "" }, apply: { applyText($0) }) { message in
963 self.panel = nil
964 if let message { commands.show(message) }
965 }
966 case .conflict:
967 ConflictSheet(session: session)
968 case .syncCopies:
969 SyncConflictSheet(session: session) { commands.show($0) }
970 case .recovery:
971 RecoverySheet(session: session) { commands.show($0) }
972 }
973 }
974
975 /// `new` in place of the buffer's text, as one edit, with the caret at `caret` or where it was.
976 private func applyText(_ new: String, caret: Int? = nil) {
977 guard let editor = commands.editor else { return }
978 let context = editor.context()
979 let caret = min(caret ?? context.caret, (new as NSString).length)
980 editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
981 }
982
983 /// `org-plot/gnuplot` for the table at the caret: through gnuplot when it's installed, as
984 /// Emacs runs it, else drawn here; written to `file:` when the options name one, else shown.
985 private func plotTable() {
986 guard let editor = commands.editor, let path = session.path else { return commands.show("No file is open") }
987 let context = editor.context()
988 let plot: TablePlot.Plot
989 do { plot = try TablePlot.plot(context.text, at: context.caret) } catch { return commands.show("\(error)") }
990 let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
991 #if !APPSTORE
992 if let gnuplot = PlotOutput.gnuplot {
993 commands.show("Plotting with gnuplot…")
994 Task {
995 do {
996 let image = try await PlotOutput.runGnuplot(plot, directory: directory, gnuplot: gnuplot)
997 if plot.options.file == nil { panel = .plotImage(UUID(), image) } else { plotWritten(image, editor: editor) }
998 } catch {
999 commands.show("\(error)")
1000 }
1001 }
1002 return
1003 }
1004 #endif
1005 if let url = PlotOutput.file(plot, directory: directory) {
1006 guard reach([url.path]) else { return }
1007 do {
1008 try PlotOutput.write(plot, to: url)
1009 plotWritten(url, editor: editor, note: PlotOutput.note(plot))
1010 } catch {
1011 commands.show("\(error)")
1012 }
1013 } else {
1014 do { try PlotOutput.check(plot) } catch { return commands.show("\(error)") }
1015 panel = .plot(UUID(), plot)
1016 if let note = PlotOutput.note(plot) { commands.show(note) }
1017 }
1018 }
1019
1020 /// The image is where `file:` says; a link to it shows it again.
1021 private func plotWritten(_ url: URL, editor: OrgEditor, note: String? = nil) {
1022 commands.show("Plot written to \(url.lastPathComponent)" + (note.map { ". " + $0 } ?? ""))
1023 if editor.showsImages { editor.refreshImages() }
1024 }
1025
1026 /// `org-publish`, `org-publish-all`, `org-publish-current-file` and
1027 /// `org-publish-current-project`, with the projects in config.toml.
1028 private func publish(_ id: String) {
1029 let config = (try? String(contentsOf: UserConfig.file("config.toml"), encoding: .utf8)) ?? ""
1030 let loaded = Publish.projects(fromConfig: config, root: workspace.rootPaths.first)
1031 if let problem = loaded.problems.first { commands.show(problem) }
1032 guard !loaded.projects.isEmpty else { return commands.show("No [[publish]] projects in config.toml") }
1033 let read = { (path: String) -> String? in
1034 session.openDocuments.first { $0.path == path }?.document.text ?? (try? String(contentsOfFile: path, encoding: .utf8))
1035 }
1036 let codeStyle = HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme)
1037 func run(_ chosen: [PublishProject], only: String? = nil) {
1038 // The chosen projects and their components read and write these folders.
1039 let involved = { loaded.projects.filter { project in chosen.contains { $0 == project || $0.components.contains(project.name) } } }
1040 guard reach(involved().flatMap { [$0.baseDirectory, $0.publishingDirectory] }, directories: true) else { return }
1041 do {
1042 let report = try Publish.publish(chosen, all: loaded.projects, only: only, read: read) { function, text, path, bodyOnly in
1043 try Publish.export(function, text: text, path: path, bodyOnly: bodyOnly, settings: Preferences.orgSettings, codeStyle: codeStyle)
1044 }
1045 commands.show("Published \(report.published.count) files" + (report.skipped.isEmpty ? "" : ", \(report.skipped.count) up to date"))
1046 } catch {
1047 commands.show("\(error)")
1048 }
1049 }
1050 let current = session.path.map { Publish.projects(containing: $0, in: loaded.projects) } ?? []
1051 switch id {
1052 case "app.publish.all":
1053 run(loaded.projects)
1054 case "app.publish.current-file":
1055 guard let path = session.path, !current.isEmpty else { return commands.show("File is not part of any known project") }
1056 run([current[0]], only: path)
1057 case "app.publish.current-project":
1058 guard !current.isEmpty else { return commands.show("File is not part of any known project") }
1059 run([current[0]])
1060 default:
1061 let names = loaded.projects.map(\.name)
1062 commands.ask(Prompt(key: "project", message: "Publish project:", choices: names)) { answer in
1063 guard let answer, let project = loaded.projects.first(where: { $0.name == answer }) else { return }
1064 run([project])
1065 }
1066 }
1067 }
1068
1069 /// Work a command hands to the platform: tables recalculated in Emacs.
1070 private func runExternal(_ request: ExternalRequest) {
1071 switch request {
1072 case .openLink(let link):
1073 if let message = LinkOpener.open(link, session: session, workspace: workspace, ask: commands.ask, elisp: runElispLink) { commands.show(message) }
1074 // `org-occur` for a regexp link, once the editor shows the file.
1075 if let regexp = Links.regexpSearch(link) {
1076 DispatchQueue.main.async { commands.editor?.perform(SparseTreeCommand(), answers: ["sparse": "/", "regexp": regexp]) }
1077 }
1078 case .tangle(let scope):
1079 guard ProAccess.shared.allows(.babel), reach(session.tangleFiles(scope)) else { return }
1080 commands.show(session.tangle(scope))
1081 case .agenda(let start, let days):
1082 commands.agendaRequest = (start, days)
1083 openWindow(id: "agenda")
1084 case .editBlock(let edit):
1085 blockEdit = BlockEditRequest(edit: edit)
1086 case .columnView(let view):
1087 panel = .columns(UUID(), view)
1088 #if APPSTORE
1089 case .emacsTable(_, _, _, let reason, _, let formula, let partial):
1090 // The fields written before the formula stay, as Emacs leaves them when a formula fails.
1091 if let partial { commands.editor?.perform(PrecomputedEdit(partial)) }
1092 if reason == TableBlocks.lockedReason {
1093 ProAccess.shared.allows(.babel)
1094 return
1095 }
1096 if let formula {
1097 commands.show(String(localized: "The table was recalculated up to \(formula), which can't be calculated here: \(TableReason.localized(reason)).", comment: "Table formulas orgstar calculated up to one it can't"))
1098 } else {
1099 commands.show(String(localized: "This table's formulas can't be calculated here: \(TableReason.localized(reason)).", comment: "Table formulas orgstar can't calculate"))
1100 }
1101 #else
1102 case .emacsTable(let table, let point, let form, let reason, let lisp, let formula, let partial):
1103 // Emacs runs the blocks `org-sbe` names without asking, so they need Babel, and
1104 // the question below each time.
1105 let blocks = reason == TableBlocks.lockedReason || session.document?.text.contains("org-sbe") == true
1106 if blocks, !ProAccess.shared.allows(.babel) {
1107 if let partial { commands.editor?.perform(PrecomputedEdit(partial)) }
1108 return
1109 }
1110 guard EmacsRunner.executable() != nil else {
1111 // Without Emacs this is the App Store build's case: keep the fields written so far.
1112 if let partial { commands.editor?.perform(PrecomputedEdit(partial)) }
1113 if let formula {
1114 return commands.show(String(localized: "The table was recalculated up to \(formula), which can't be calculated here: \(TableReason.localized(reason)).", comment: "Table formulas orgstar calculated up to one it can't"))
1115 }
1116 return commands.show(String(localized: "This table's formulas can't be calculated here: \(TableReason.localized(reason)).", comment: "Table formulas orgstar can't calculate"))
1117 }
1118 let run = {
1119 commands.show(String(localized: "Recalculating in Emacs (\(TableReason.localized(reason)))…", comment: "Table formulas sent to Emacs, and why"))
1120 commands.runInEmacs { commands.show(await session.recalculateInEmacs(table: table, point: point, form: form)) }
1121 }
1122 guard lisp, let path = session.path, let text = session.document?.text else { return run() }
1123 let content = (text as NSString).substring(with: NSRange(location: table.lowerBound, length: min((text as NSString).length, table.upperBound + 2000) - table.lowerBound))
1124 if !blocks, trust.isTrusted(path: path, content: content) { return run() }
1125 let message = blocks ? "This table's formulas run Lisp and source blocks. Run them? (yes, no)" : "This table's formulas run Lisp. Run them? (yes, no, always)"
1126 commands.ask(Prompt(key: "confirm", message: message, choices: blocks ? ["yes", "no"] : ["yes", "no", "always"])) { answer in
1127 switch answer {
1128 case "always":
1129 trust.trust(path: path, content: content)
1130 run()
1131 case "yes": run()
1132 default: commands.show("Not recalculated")
1133 }
1134 }
1135 #endif
1136 case .babel(let job):
1137 guard ProAccess.shared.allows(.babel) else { return }
1138 let run = {
1139 guard reach(session.resultFile(of: job).map { [$0] } ?? []) else { return }
1140 commands.show("Running \(job.language) block… (⌘. to cancel)")
1141 session.startBabel(job) { commands.show($0) }
1142 }
1143 guard let path = session.path else { return }
1144 if !job.alwaysAsk, trust.isTrusted(path: path, content: job.blockText) { return run() }
1145 let choices = job.alwaysAsk ? ["yes", "no"] : ["yes", "no", "always"]
1146 commands.ask(Prompt(key: "confirm", message: "Run this \(job.language) block? (\(choices.joined(separator: ", ")))", choices: choices)) { answer in
1147 switch answer {
1148 case "always":
1149 trust.trust(path: path, content: job.blockText)
1150 run()
1151 case "yes": run()
1152 default: commands.show("Not run")
1153 }
1154 }
1155 }
1156 }
1157
1158 /// Runs an `elisp:` link's form once trusted, asking as `org-link-elisp-confirm-function` does.
1159 private func runElispLink(_ form: String) {
1160 let run = { _ = Task { commands.show(await session.evaluateLink(form)) } }
1161 let content = "elisp:" + form
1162 if let path = session.path, trust.isTrusted(path: path, content: content) { return run() }
1163 let choices = session.path == nil ? ["yes", "no"] : ["yes", "no", "always"]
1164 commands.ask(Prompt(key: "confirm", message: "Execute \(form) as Elisp? (\(choices.joined(separator: ", ")))", choices: choices)) { answer in
1165 switch answer {
1166 case "always":
1167 if let path = session.path { trust.trust(path: path, content: content) }
1168 run()
1169 case "yes": run()
1170 default: commands.show("Not run")
1171 }
1172 }
1173 }
1174
1175 private struct ReminderKey: Equatable {
1176 var enabled: Bool
1177 var lead: Int
1178 var subfolders: Bool
1179 /// The widgets leave out hidden folders.
1180 var hidden: Set<String>
1181 var files: Int
1182 var changed: Int?
1183 var edits: Int
1184 var hour: Int
1185 /// The widgets' colors.
1186 var theme: ThemeSpec
1187 }
1188
1189 /// Sets the notifications for the next week's timed entries, once edits pause.
1190 private func updateReminders() async {
1191 guard let scheduler else { return }
1192 guard remindersEnabled else {
1193 await scheduler.clear()
1194 return
1195 }
1196 guard !Task.isCancelled, !workspace.files.isEmpty else { return }
1197 let agenda = reminderAgenda ?? AgendaModel(workspace: workspace)
1198 reminderAgenda = agenda
1199 agenda.includeSubfolders = agendaSubfolders
1200 agenda.excludeArchives = OrgPreferences.agendaExcludeArchives()
1201 let open = session.openTexts
1202 let reminders = await agenda.reminders(open: open, lead: reminderLead)
1203 guard !Task.isCancelled else { return }
1204 await scheduler.reconcile(reminders)
1205 }
1206
1207 /// The desktop widgets' agenda and habits, written where the widget extension reads them,
1208 /// with the widgets reloaded when they changed; and today's agenda for the menu bar item.
1209 private func updateWidgets() async {
1210 let file = ProAccess.shared.isUnlocked ? AgendaSnapshot.file() : nil
1211 guard !Task.isCancelled, !workspace.files.isEmpty, file != nil || menuBarItem else { return }
1212 let days = widgetAgenda ?? AgendaModel(workspace: workspace)
1213 widgetAgenda = days
1214 days.mode = .agenda(span: AgendaSnapshot.dayCount, startOffset: 0)
1215 days.startOnWeekday = nil
1216 days.includeSubfolders = agendaSubfolders
1217 days.excludeArchives = OrgPreferences.agendaExcludeArchives()
1218 days.hiddenFolders = HiddenFolders.shared.all
1219 days.agendaFiles = OrgPreferences.agendaFiles()
1220 days.options = OrgPreferences.agendaOptions(days.options)
1221 days.options.logMode = false
1222 days.calendarEvents = ProAccess.shared.isUnlocked && OrgPreferences.calendarEvents() && CalendarEvents.isAuthorized ? CalendarAccess.events : nil
1223 days.calendarNames = OrgPreferences.calendarEventCalendars()
1224 days.reminderLists = ProAccess.shared.isUnlocked && OrgPreferences.agendaReminders() && ReminderLists.isAuthorized ? CalendarAccess.reminders : nil
1225 days.reminderListNames = OrgPreferences.agendaReminderLists()
1226 let open = session.openTexts
1227 await days.refresh(open: open)
1228 guard !Task.isCancelled else { return }
1229 let snapshot = AgendaSnapshot(groups: days.groups(), today: days.today, theme: theme, generated: Date())
1230 menuToday = snapshot.days.first.map { $0.overdue + $0.rows } ?? []
1231 guard let file else { return }
1232 if (try? HabitSnapshot(habits: await days.habits(open: open), theme: theme).write()) == true {
1233 WidgetCenter.shared.reloadTimelines(ofKind: "sh.krz.orgstar.habits")
1234 }
1235 if (try? snapshot.write(to: file)) == true { WidgetCenter.shared.reloadAllTimelines() }
1236 }
1237
1238 private func loadKeymap() {
1239 let loaded = KeymapLoader.load(preset, commands: Set(EditorCommands.all.map(\.id)))
1240 keymap = loaded.keymap
1241 commands.keymap = loaded.keymap
1242 commands.modal = preset.isModal
1243 if let first = loaded.problems.first {
1244 let more = loaded.problems.count > 1 ? " (and \(loaded.problems.count - 1) more)" : ""
1245 commands.show("keymap.toml: \(first)\(more)")
1246 }
1247 }
1248
1249 /// `SPC b b`: open buffers, most recent first, by name (with the folder when names repeat).
1250 private func switchBuffer() {
1251 let paths = session.recentPaths.dropFirst() + session.recentPaths.prefix(1)
1252 let labels = paths.map(session.bufferName)
1253 guard !labels.isEmpty else { return commands.show("No buffers are open") }
1254 commands.ask(Prompt(key: "buffer", message: "Switch to buffer:", choices: labels)) { answer in
1255 guard let answer, let index = labels.firstIndex(of: answer) else { return }
1256 session.open(Array(paths)[index])
1257 }
1258 }
1259
1260 /// Runs a command from a key, the palette or the Org menu.
1261 private func perform(_ id: String) {
1262 if hiddenCommandIDs.contains(id) {
1263 if let replacement = AppStoreCommands.replacement(for: id) { return perform(replacement) }
1264 return commands.show(Self.unavailable(EditorCommands.all.first { $0.id == id }?.title ?? id))
1265 }
1266 if let feature = ProFeature.required(byCommand: id), !ProAccess.shared.allows(feature) { return }
1267 let orgOnly = ["app.refile", "app.refile.copy", "app.archive", "app.clock.in", "app.clock.default", "app.copy-rich-text", "app.export-subtree", "app.export-body-only"].contains(id) || (id.hasPrefix("app.export.") && !id.hasPrefix("app.export.icalendar-")) || id.hasPrefix("org.")
1268 if orgOnly, !session.isOrg {
1269 commands.show("Not an org file")
1270 return
1271 }
1272 switch id {
1273 case "app.save":
1274 if !session.save(), session.conflict != nil { commands.showingConflict = true }
1275 case "app.quit": NSApp.terminate(nil)
1276 case "app.save-all":
1277 if !session.saveAll(), session.conflict != nil { commands.showingConflict = true }
1278 case "app.buffer.switch": switchBuffer()
1279 case "app.buffer.next": session.cycle(1)
1280 case "app.buffer.previous": session.cycle(-1)
1281 case "app.buffer.last": session.showPrevious()
1282 case "app.buffer.kill":
1283 if let window = paneWindow, window.paneCount > 1 {
1284 window.closeTab(session.path, in: window.focusedPane, commands: commands)
1285 } else if let path = session.path {
1286 if UnsavedChanges.resolve(session) { session.kill(path) }
1287 } else {
1288 NSApp.keyWindow?.performClose(nil)
1289 }
1290 case "app.buffer.kill-others":
1291 let others = session.openPaths.filter { $0 != session.path }
1292 if UnsavedChanges.resolve(session, paths: others) { others.forEach(session.kill) }
1293 case "app.buffer.kill-all":
1294 let all = session.openPaths
1295 if UnsavedChanges.resolve(session, paths: all) { all.forEach(session.kill) }
1296 case "app.toggle-tab-bar": showTabBar.toggle()
1297 case "app.split-below": paneWindow?.split(.vertical)
1298 case "app.split-right": paneWindow?.split(.horizontal)
1299 case "app.pane-close":
1300 guard let window = paneWindow, window.paneCount > 1 else { return commands.show("Attempt to delete the only pane") }
1301 commands.store.releasePane(window.focused)
1302 window.close(window.focused)
1303 focusPane(window)
1304 case "app.pane-only":
1305 guard let window = paneWindow else { return }
1306 for id in window.layout.panes where id != window.focused { commands.store.releasePane(id) }
1307 window.closeOthers()
1308 focusPane(window)
1309 case "app.pane-next":
1310 guard let window = paneWindow else { return }
1311 window.focusNext()
1312 focusPane(window)
1313 case "app.window-new": openWindow(id: "editor")
1314 case "app.babel.cancel":
1315 if session.isRunningBabel {
1316 session.cancelBabel()
1317 } else if let task = commands.emacsTask {
1318 task.cancel()
1319 } else {
1320 commands.show("Nothing is running")
1321 }
1322 case "app.toggle-outline": toggleOutline()
1323 case "app.toggle-backlinks": backlinksShown.toggle()
1324 case "app.toggle-inspector": inspectorShown.toggle()
1325 case "app.toggle-markup": showMarkup.toggle()
1326 case "app.toggle-line-numbers": showLineNumbers.toggle()
1327 case "app.import-emacs": showingImport = true
1328 case "app.edit-config": commands.jump(path: UserConfig.configFile.path, offset: 0)
1329 case "app.quick-open": commands.showingQuickOpen = true
1330 case "app.palette": commands.showingPalette = true
1331 case "app.messages": commands.showingMessages = true
1332 case "app.search": commands.focusSearch = true
1333 case "app.reload-keymap":
1334 loadKeymap()
1335 commands.show("Keymap reloaded")
1336 case "app.refile", "app.refile.copy":
1337 let keep = id == "app.refile.copy"
1338 let targets = workspace.refileTargets(openPath: session.path, document: session.document)
1339 commands.ask(Prompt(key: "refile", message: keep ? "Copy to:" : "Refile to:", choices: targets.map(\.label))) { answer in
1340 guard let answer else { return }
1341 if let target = targets.first(where: { $0.label == answer }) {
1342 if let message = session.refile(to: target, keep: keep) { commands.show(message) }
1343 return
1344 }
1345 // `org-refile-allow-creating-parent-nodes`: `parent/new` adds the heading first.
1346 let creating = OrgPreferences.refileSettings().creating
1347 guard creating != .no, let (parent, child) = RefileSettings.newNode(answer, in: targets) else { return commands.show("Invalid target location") }
1348 let create = {
1349 switch session.createRefileChild(under: parent, title: child) {
1350 case .success(let target): if let message = session.refile(to: target, keep: keep) { commands.show(message) }
1351 case .failure(.message(let message)): commands.show(message)
1352 }
1353 }
1354 guard creating == .confirm else { return create() }
1355 commands.ask(Prompt(key: "confirm", message: "Create new node \"\(child)\"?", choices: ["yes", "no"])) { reply in
1356 if reply == "yes" { create() }
1357 }
1358 }
1359 case "app.refile.goto":
1360 // `C-u C-c C-w`: the target heading, or the end of a file.
1361 let targets = workspace.refileTargets(openPath: session.path, document: session.document)
1362 commands.ask(Prompt(key: "refile", message: "Goto:", choices: targets.map(\.label))) { answer in
1363 guard let answer, let target = targets.first(where: { $0.label == answer }) else { return }
1364 commands.jump(path: target.path, offset: target.start ?? Int.max)
1365 }
1366 case "app.archive":
1367 guard reach(session.archiveFile().map { [$0] } ?? []) else { return }
1368 if let message = session.archive() { commands.show(message) }
1369 case "app.table-import":
1370 // `org-table-import`: a TSV, CSV or space-separated file becomes a table at point.
1371 guard let editor = commands.editor else { return commands.show("No file is open") }
1372 let panel = NSOpenPanel()
1373 panel.allowedContentTypes = [.commaSeparatedText, .tabSeparatedText, .plainText]
1374 guard panel.runModal() == .OK, let url = panel.url else { return }
1375 guard let contents = try? String(contentsOf: url, encoding: .utf8) else { return commands.show("Can't read \(url.lastPathComponent)") }
1376 editor.perform(ImportTable(contents: contents))
1377 case "app.table-export":
1378 // `org-table-export`: CSV for a .csv name, else TSV.
1379 guard let editor = commands.editor else { return commands.show("No file is open") }
1380 let context = editor.context()
1381 guard ImportTable.exportText(context.text, at: context.caret, path: "") != nil else { return commands.show("No table at point") }
1382 let panel = NSSavePanel()
1383 panel.nameFieldStringValue = "table.csv"
1384 guard panel.runModal() == .OK, let url = panel.url,
1385 let text = ImportTable.exportText(context.text, at: context.caret, path: url.path) else { return }
1386 do {
1387 try text.write(to: url, atomically: true, encoding: .utf8)
1388 commands.show("Export done.")
1389 } catch {
1390 commands.show("File not written: \(error.localizedDescription)")
1391 }
1392 case "org.subtree.paste":
1393 guard let text = NSPasteboard.general.string(forType: .string) else { return commands.show("The clipboard is empty") }
1394 commands.editor?.perform(PasteSubtree(text: text))
1395 case "org.link.insert":
1396 commands.editor?.perform(InsertLink(stored: commands.storedLinks, file: session.path))
1397 case "org.link.store":
1398 guard let editor = commands.editor, let path = session.path else { return commands.show("No method for storing a link from this buffer") }
1399 let context = editor.context()
1400 let denote = OrgPreferences.usesDenote() ? Links.storeDenote(in: context, path: path) : nil
1401 commands.storeLink(denote ?? Links.store(in: context, path: Links.abbreviate(path, home: OrgPaths.home)))
1402 case "org.id.store-link":
1403 guard let editor = commands.editor, let path = session.path else { return }
1404 if case .commit = editor.perform(CreateID()),
1405 let link = Links.storeID(in: editor.context(), fileName: (path as NSString).lastPathComponent) {
1406 commands.storeLink(link)
1407 }
1408 case "app.agenda":
1409 openWindow(id: "agenda")
1410 case "app.clock.in":
1411 clockIn(.caret)
1412 case "app.clock.in-recent":
1413 clockIn(.select)
1414 case "app.clock.in-last":
1415 clockIn(.last)
1416 case let id where id.hasPrefix("app.clock.history."):
1417 if let index = Int(id.dropFirst("app.clock.history.".count)), index < clock.history.count { clockIn(.task(clock.history[index])) }
1418 case "app.clock.out":
1419 commands.show(clock.clockOut(session))
1420 case "app.clock.cancel":
1421 commands.show(clock.clockOut(session, cancel: true))
1422 case "app.clock.goto":
1423 let found = clock.goto(session)
1424 if let location = found.location { commands.jump(path: location.path, offset: location.offset) }
1425 if let message = found.message { commands.show(message) }
1426 case "app.clock.goto-recent":
1427 Task {
1428 let found = await clock.gotoRecent(session, ask: askClock)
1429 if let location = found.location { commands.jump(path: location.path, offset: location.offset) }
1430 if let message = found.message { commands.show(message) }
1431 }
1432 case "app.clock.default":
1433 commands.show(clock.markDefault(session))
1434 case "app.clock.resolve":
1435 Task { report(await clock.resolveOpenClocks(session, paths: orgFiles, ask: askClock)) }
1436 case "app.clock.report":
1437 openWindow(id: "clock-report")
1438 case "app.board":
1439 openWindow(id: "board")
1440 case "app.node.graph":
1441 openWindow(id: "graph")
1442 case "app.sidebar-agenda":
1443 sidebarAgenda.toggle()
1444 case "app.capture":
1445 NSApp.activate()
1446 openWindow(id: "capture")
1447 case "app.revert":
1448 // `:e`: the file as it is on disk; unsaved changes go to recovery.
1449 guard session.path != nil else { return commands.show("No file is open") }
1450 session.useDiskVersion()
1451 commands.show("Reverted to the file on disk")
1452 case "app.sync-conflicts":
1453 guard session.path != nil else { return commands.show("No file is open") }
1454 panel = .syncCopies(UUID())
1455 case "app.recovery":
1456 guard session.path != nil else { return commands.show("No file is open") }
1457 panel = .recovery(UUID())
1458 case "app.copy-rich-text":
1459 copyRichText()
1460 case "app.export-dialog":
1461 guard let path = session.path else { return commands.show("No file is open") }
1462 panel = .export(UUID(), URL(fileURLWithPath: path))
1463 case "app.export-subtree", "app.export-body-only":
1464 guard let path = session.path else { return commands.show("No file is open") }
1465 var settings = ExportSettings.saved(for: path)
1466 if id == "app.export-subtree" {
1467 settings.subtree.toggle()
1468 commands.show(settings.subtree ? "Export commands: subtree at the caret" : "Export commands: whole file")
1469 } else {
1470 settings.bodyOnly.toggle()
1471 commands.show(settings.bodyOnly ? "Export commands: body only" : "Export commands: whole document")
1472 }
1473 settings.save(for: path)
1474 case let id where id.hasPrefix("app.export."):
1475 let format = String(id.dropFirst("app.export.".count))
1476 guard let options = (session.path.map { ExportSettings.saved(for: $0) } ?? ExportSettings()).commandOptions(format) else {
1477 return commands.show(ExportSettings.noBodyOnly)
1478 }
1479 export(format, subtree: options.subtree, bodyOnly: options.bodyOnly)
1480 case let id where id.hasPrefix("app.publish"):
1481 publish(id)
1482 case "app.plot":
1483 plotTable()
1484 case let id where id.hasPrefix("app.crypt."):
1485 crypt(id)
1486 case let id where id.hasPrefix("app.attach."):
1487 guard reach(attachActions.entry().flatMap { Attachments.directory($0, noFSCheck: true) }.map { [$0] } ?? [], directories: true) else { return }
1488 attachActions.run(id)
1489 case let id where id.hasPrefix("app.dailies.") || id.hasPrefix("app.node."):
1490 roamActions.run(id)
1491 default:
1492 if let editor = commands.editor { editor.run(id) } else { commands.show("No file is open") }
1493 }
1494 }
1495
1496 private var askClock: ClockModel.Ask { commands.askClock }
1497
1498 /// The files `org-resolve-clocks` looks through: the workspace's org files.
1499 private var orgFiles: [String] { workspace.files.filter { $0.kind == .org }.map(\.path) }
1500
1501 private func clockIn(_ target: ClockModel.Target) {
1502 Task { report(await clock.clockIn(session, target: target, paths: orgFiles, ask: askClock)) }
1503 }
1504
1505 /// The last message of a clock command, and the clock to show for `j`.
1506 private func report(_ outcome: ClockModel.Outcome) {
1507 if let jump = outcome.jump { commands.jump(path: jump.path, offset: jump.offset) }
1508 if let message = outcome.messages.last(where: { !$0.isEmpty }) { commands.show(message) }
1509 }
1510
1511 private var errorShown: Binding<Bool> {
1512 Binding(get: { workspace.lastError != nil || session.lastError != nil }, set: { _ in })
1513 }
1514}