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