Sources/Orgstar/ContentView.swift

524b5afe95ec3f3e3d1daba761a9e181f09cf88a
orgstar/Sources/Orgstar/ContentView.swift history · blame · raw

946 lines · 50596 bytes

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