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