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