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