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