Sources/Orgstar/ContentView.swift

d85099bc95bf1766aee990d94671dacda0c0686e
orgstar/Sources/Orgstar/ContentView.swift history · blame · raw

954 lines · 51095 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, run: runInColumnView, document: { session.document.map { ($0.text, $0.tree) } }) { offset in
334                    commands.editor?.reveal(offset)
335                }
336            case .export(_, let source):
337                ExportSheet(source: source, inSubtree: exportSubtreeAvailable, target: exportTarget) { format, destination, open, subtree, bodyOnly in
338                    export(format, to: destination, open: open, subtree: subtree, bodyOnly: bodyOnly)
339                }
340            case .conflict:
341                ConflictSheet(session: session)
342            case .syncCopies:
343                SyncConflictSheet(session: session) { commands.show($0) }
344            case .recovery:
345                RecoverySheet(session: session) { commands.show($0) }
346            }
347        }
348        .sheet(item: $blockEdit) { request in
349            BlockEditorView(edit: request.edit) { content in
350                blockEdit = nil
351                guard let content else { return }
352                commands.editor?.perform(ReplaceBlockLines(edit: request.edit, content: content))
353            }
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        }
465        .task {
466            while !Task.isCancelled {
467                try? await Task.sleep(for: .seconds(3600))
468                hour += 1
469            }
470        }
471        // `org-resolve-clocks-if-idle`, checked every minute while a clock runs.
472        .task(id: "\(clock.running?.start ?? "") \(clockIdleTime)") {
473            guard clock.running != nil, clockIdleTime > 0 else { return }
474            while !Task.isCancelled {
475                try? await Task.sleep(for: .seconds(60))
476                guard !Task.isCancelled, clock.running != nil, !clock.isResolving else { continue }
477                let idle = ClockIdle.seconds()
478                guard idle > Double(clockIdleTime * 60) else { continue }
479                NSApp.requestUserAttention(.informationalRequest)
480                report(await clock.resolveIdle(session, idleSince: Date().addingTimeInterval(-idle), ask: askClock))
481            }
482        }
483        .task {
484            DevelopmentHooks.scheduleSnapshot()
485            pendingCarets = BufferRestore.restore(session)
486            if let path = session.path, let caret = pendingCarets.removeValue(forKey: path) { session.reveal(caret) }
487            // Files handed over at launch open after the restored buffers, and show.
488            for path in AppDelegate.pendingOpens { session.open(path) }
489            AppDelegate.pendingOpens = []
490            for link in AppDelegate.pendingLinks + [DevelopmentHooks.urlToOpen].compactMap({ $0 }) { commands.handle(protocolURL: link) }
491            AppDelegate.pendingLinks = []
492            if let path = DevelopmentHooks.fileToOpen { selectedFile = path }
493            if let root = DevelopmentHooks.rootToAdd { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
494            if let commandList = DevelopmentHooks.commandToRun {
495                // The file opened above needs its editor first.
496                for _ in 0..<20 where DevelopmentHooks.fileToOpen != nil && commands.editor == nil { try? await Task.sleep(for: .milliseconds(100)) }
497                for command in commandList.split(separator: ",") { perform(String(command)) }
498                for answer in DevelopmentHooks.answers {
499                    for _ in 0..<20 where commands.prompt == nil { try? await Task.sleep(for: .milliseconds(100)) }
500                    commands.answer(answer)
501                }
502            }
503            if let id = DevelopmentHooks.windowToOpen {
504                if id == "settings" { openSettings() } else { openWindow(id: id) }
505            }
506            await workspace.refresh()
507            workspace.startWatching()
508        }
509    }
510
511    /// The selection, or the whole file without one, on the clipboard as HTML, RTF and plain
512    /// text, to paste formatted into mail and documents.
513    private func copyRichText() {
514        guard let path = session.path, let whole = session.document?.text, let editor = commands.editor else { return commands.show("No file is open") }
515        let defaults = Preferences.orgSettings.resolvingSetupFiles(in: whole, path: path, read: OrgSettings.readFile)
516        let selection = editor.context().selection.first { !$0.isEmpty }
517        let selected = selection.map { (whole as NSString).substring(with: NSRange($0)) }
518        let url = URL(fileURLWithPath: path)
519        let html = HTMLExport.page(
520            selected ?? whole, fallbackTitle: url.deletingPathExtension().lastPathComponent, settings: defaults, path: path, bodyOnly: selected != nil,
521            codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme)
522        )
523        do {
524            try RichTextExport.copy(html: html, directory: url.deletingLastPathComponent())
525            commands.show(selected == nil ? "Copied the file as rich text" : "Copied the selection as rich text")
526        } catch {
527            commands.show("\(error)")
528        }
529    }
530
531    /// Whether the caret is in a heading's subtree, which the export dialog can export alone.
532    private var exportSubtreeAvailable: Bool {
533        guard let text = session.document?.text, let caret = commands.editor?.context().caret else { return false }
534        return ExportScope.subtree(text, at: caret) != nil
535    }
536
537    /// Where an export goes by default: `#+EXPORT_FILE_NAME`, or the subtree's
538    /// `EXPORT_FILE_NAME`, else beside the file, with `ext`.
539    private func exportTarget(_ ext: String, subtree: Bool) -> URL {
540        let path = session.path ?? ""
541        let text = session.document?.text ?? ""
542        let caret = subtree ? commands.editor?.context().caret : nil
543        return ExportScope.output(for: URL(fileURLWithPath: path), name: ExportScope.fileName(text, subtreeAt: caret), extension: ext)
544    }
545
546    /// Writes the export where `#+EXPORT_FILE_NAME` says or beside the file, as Emacs's export
547    /// dispatcher does, or to `destination`, and opens it with `open`. `subtree` exports the
548    /// subtree at the caret alone; `bodyOnly` leaves out the title and page wrapper.
549    private func export(_ format: String, to destination: URL? = nil, open: Bool = false, subtree: Bool = false, bodyOnly: Bool = false) {
550        guard let path = session.path, var text = session.document?.text else {
551            commands.show("No file is open")
552            return
553        }
554        let url = URL(fileURLWithPath: path)
555        let base = url.deletingPathExtension()
556        let defaults = Preferences.orgSettings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
557        let open = open || format == "html-open"
558        let caret = commands.editor?.context().caret ?? 0
559        let whole = text
560        if subtree {
561            guard let narrowed = ExportScope.subtree(text, at: caret, settings: defaults) else { return commands.show("Not in a subtree") }
562            text = narrowed
563        }
564        switch format {
565        case "html", "html-open", "markdown":
566            let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
567            let target = destination ?? ExportScope.output(for: url, name: name, extension: format == "markdown" ? "md" : "html")
568            let content = format == "markdown"
569                ? MarkdownExport.document(text, settings: defaults, path: path, bodyOnly: bodyOnly)
570                : HTMLExport.page(
571                    text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path, bodyOnly: bodyOnly,
572                    codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme)
573                )
574            do {
575                try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
576                try content.write(to: target, atomically: true, encoding: .utf8)
577                commands.show("Exported to \(target.lastPathComponent)")
578                if open { NSWorkspace.shared.open(target) }
579            } catch {
580                commands.show("Can't write \(target.lastPathComponent): \(error.localizedDescription)")
581            }
582        case "print-pdf", "docx", "rtf", "plain-text":
583            let ext = ["print-pdf": "pdf", "plain-text": "txt"][format] ?? format
584            let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
585            let target = destination ?? ExportScope.output(for: url, name: name, extension: ext)
586            let html = HTMLExport.page(
587                text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path,
588                codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme)
589            )
590            let directory = url.deletingLastPathComponent()
591            if format == "print-pdf" { commands.show("Exporting to PDF…") }
592            Task {
593                do {
594                    let data: Data
595                    switch format {
596                    case "print-pdf": data = try await PDFExport.pdf(html: html, directory: directory)
597                    case "docx": data = try RichTextExport.docx(RichTextExport.attributed(html: html, directory: directory))
598                    case "rtf": data = try RichTextExport.rtf(RichTextExport.attributed(html: html, directory: directory))
599                    default: data = Data(RichTextExport.plain(try RichTextExport.attributed(html: html, directory: directory)).utf8)
600                    }
601                    try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
602                    try data.write(to: target, options: .atomic)
603                    commands.show("Exported to \(target.lastPathComponent)")
604                    if open { NSWorkspace.shared.open(target) }
605                } catch {
606                    commands.show("Can't export \(target.lastPathComponent): \(error)")
607                }
608            }
609        default:
610            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"]
611            guard let function = functions[format] else { return }
612            commands.show("Exporting with Emacs…")
613            commands.runInEmacs {
614                do {
615                    // Emacs narrows to the subtree and reads EXPORT_FILE_NAME itself.
616                    let point = subtree ? (whole as NSString).substring(to: min(caret, (whole as NSString).length)).unicodeScalars.count + 1 : nil
617                    var written = URL(fileURLWithPath: try await EmacsRunner.export(
618                        text: whole, path: path, function: function, subtree: point, bodyOnly: bodyOnly
619                    ))
620                    if let destination, destination.standardizedFileURL != written.standardizedFileURL {
621                        try? FileManager.default.removeItem(at: destination)
622                        try FileManager.default.moveItem(at: written, to: destination)
623                        written = destination
624                    }
625                    commands.show("Exported to \(written.lastPathComponent)")
626                    if open { NSWorkspace.shared.open(written) }
627                } catch is CancellationError {
628                    commands.show("Export canceled")
629                } catch {
630                    commands.show("\(error)")
631                }
632            }
633        }
634    }
635
636    /// Work a command hands to the platform: tables recalculated in Emacs.
637    private func runExternal(_ request: ExternalRequest) {
638        switch request {
639        case .openLink(let link):
640            if let message = LinkOpener.open(link, session: session, workspace: workspace) { commands.show(message) }
641            // `org-occur` for a regexp link, once the editor shows the file.
642            if let regexp = Links.regexpSearch(link) {
643                DispatchQueue.main.async { commands.editor?.perform(SparseTreeCommand(), answers: ["sparse": "/", "regexp": regexp]) }
644            }
645        case .tangle(let scope):
646            commands.show(session.tangle(scope))
647        case .agenda(let start, let days):
648            commands.agendaRequest = (start, days)
649            openWindow(id: "agenda")
650        case .editBlock(let edit):
651            blockEdit = BlockEditRequest(edit: edit)
652        case .columnView(let view):
653            panel = .columns(UUID(), view)
654        case .emacsTable(let table, let point, let form, let reason, let lisp):
655            let run = {
656                commands.show("Recalculating in Emacs (\(reason))…")
657                commands.runInEmacs { commands.show(await session.recalculateInEmacs(table: table, point: point, form: form)) }
658            }
659            guard lisp, let path = session.path, let text = session.document?.text else { return run() }
660            let content = (text as NSString).substring(with: NSRange(location: table.lowerBound, length: min((text as NSString).length, table.upperBound + 2000) - table.lowerBound))
661            if trust.isTrusted(path: path, content: content) { return run() }
662            commands.ask(Prompt(key: "confirm", message: "This table's formulas run Lisp. Run them? (yes, no, always)", choices: ["yes", "no", "always"])) { answer in
663                switch answer {
664                case "always":
665                    trust.trust(path: path, content: content)
666                    run()
667                case "yes": run()
668                default: commands.show("Not recalculated")
669                }
670            }
671        case .babel(let job):
672            let run = {
673                commands.show("Running \(job.language) block… (⌘. to cancel)")
674                session.startBabel(job) { commands.show($0) }
675            }
676            guard let path = session.path else { return }
677            if !job.alwaysAsk, trust.isTrusted(path: path, content: job.blockText) { return run() }
678            let choices = job.alwaysAsk ? ["yes", "no"] : ["yes", "no", "always"]
679            commands.ask(Prompt(key: "confirm", message: "Run this \(job.language) block? (\(choices.joined(separator: ", ")))", choices: choices)) { answer in
680                switch answer {
681                case "always":
682                    trust.trust(path: path, content: job.blockText)
683                    run()
684                case "yes": run()
685                default: commands.show("Not run")
686                }
687            }
688        }
689    }
690
691    private struct ReminderKey: Hashable {
692        var enabled: Bool
693        var lead: Int
694        var subfolders: Bool
695        var files: Int
696        var changed: Int?
697        var edits: Int
698        var hour: Int
699    }
700
701    /// Sets the notifications for the next week's timed entries, once edits pause.
702    private func updateReminders() async {
703        guard let scheduler else { return }
704        guard remindersEnabled else {
705            await scheduler.clear()
706            return
707        }
708        try? await Task.sleep(for: .seconds(2))
709        guard !Task.isCancelled, !workspace.files.isEmpty else { return }
710        let agenda = reminderAgenda ?? AgendaModel(workspace: workspace)
711        reminderAgenda = agenda
712        agenda.includeSubfolders = agendaSubfolders
713        let open = session.openTexts
714        let reminders = await agenda.reminders(open: open, lead: reminderLead)
715        guard !Task.isCancelled else { return }
716        await scheduler.reconcile(reminders)
717    }
718
719    private func loadKeymap() {
720        let loaded = KeymapLoader.load(preset, commands: Set(EditorCommands.all.map(\.id)))
721        keymap = loaded.keymap
722        commands.keymap = loaded.keymap
723        commands.modal = preset.isModal
724        if let first = loaded.problems.first {
725            let more = loaded.problems.count > 1 ? " (and \(loaded.problems.count - 1) more)" : ""
726            commands.show("keymap.toml: \(first)\(more)")
727        }
728    }
729
730    /// `SPC b b`: open buffers, most recent first, by name (with the folder when names repeat).
731    private func switchBuffer() {
732        let paths = session.recentPaths.dropFirst() + session.recentPaths.prefix(1)
733        let labels = paths.map(session.bufferName)
734        guard !labels.isEmpty else { return commands.show("No buffers are open") }
735        commands.ask(Prompt(key: "buffer", message: "Switch to buffer:", choices: labels)) { answer in
736            guard let answer, let index = labels.firstIndex(of: answer) else { return }
737            session.open(Array(paths)[index])
738        }
739    }
740
741    /// Runs a command from a key, the palette or the Org menu.
742    private func perform(_ id: String) {
743        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.")
744        if orgOnly, !session.isOrg {
745            commands.show("Not an org file")
746            return
747        }
748        switch id {
749        case "app.save":
750            if !session.save(), session.conflict != nil { commands.showingConflict = true }
751        case "app.quit": NSApp.terminate(nil)
752        case "app.save-all":
753            if !session.saveAll(), session.conflict != nil { commands.showingConflict = true }
754        case "app.buffer.switch": switchBuffer()
755        case "app.buffer.next": session.cycle(1)
756        case "app.buffer.previous": session.cycle(-1)
757        case "app.buffer.last": session.showPrevious()
758        case "app.buffer.kill":
759            guard let path = session.path else {
760                NSApp.keyWindow?.performClose(nil)
761                return
762            }
763            if UnsavedChanges.resolve(session) { session.kill(path) }
764        case "app.buffer.kill-others":
765            let others = session.openPaths.filter { $0 != session.path }
766            if UnsavedChanges.resolve(session, paths: others) { others.forEach(session.kill) }
767        case "app.buffer.kill-all":
768            let all = session.openPaths
769            if UnsavedChanges.resolve(session, paths: all) { all.forEach(session.kill) }
770        case "app.toggle-tab-bar": showTabBar.toggle()
771        case "app.split-below": paneWindow?.split(.vertical)
772        case "app.split-right": paneWindow?.split(.horizontal)
773        case "app.pane-close":
774            guard let window = paneWindow, window.paneCount > 1 else { return commands.show("Attempt to delete the only pane") }
775            commands.store.releasePane(window.focused)
776            window.close(window.focused)
777            focusPane(window)
778        case "app.pane-only":
779            guard let window = paneWindow else { return }
780            for id in window.layout.panes where id != window.focused { commands.store.releasePane(id) }
781            window.closeOthers()
782            focusPane(window)
783        case "app.pane-next":
784            guard let window = paneWindow else { return }
785            window.focusNext()
786            focusPane(window)
787        case "app.window-new": openWindow(id: "editor")
788        case "app.babel.cancel":
789            if session.isRunningBabel {
790                session.cancelBabel()
791            } else if let task = commands.emacsTask {
792                task.cancel()
793            } else {
794                commands.show("Nothing is running")
795            }
796        case "app.toggle-outline": toggleOutline()
797        case "app.toggle-backlinks": backlinksShown.toggle()
798        case "app.toggle-inspector": inspectorShown.toggle()
799        case "app.toggle-markup": showMarkup.toggle()
800        case "app.toggle-line-numbers": showLineNumbers.toggle()
801        case "app.import-emacs": showingImport = true
802        case "app.edit-config": commands.jump(path: UserConfig.configFile.path, offset: 0)
803        case "app.quick-open": commands.showingQuickOpen = true
804        case "app.palette": commands.showingPalette = true
805        case "app.search": commands.focusSearch = true
806        case "app.reload-keymap":
807            loadKeymap()
808            commands.show("Keymap reloaded")
809        case "app.refile", "app.refile.copy":
810            let keep = id == "app.refile.copy"
811            let targets = workspace.refileTargets(openPath: session.path, document: session.document)
812            commands.ask(Prompt(key: "refile", message: keep ? "Copy to:" : "Refile to:", choices: targets.map(\.label))) { answer in
813                guard let answer else { return }
814                if let target = targets.first(where: { $0.label == answer }) {
815                    if let message = session.refile(to: target, keep: keep) { commands.show(message) }
816                    return
817                }
818                // `org-refile-allow-creating-parent-nodes`: `parent/new` adds the heading first.
819                let creating = OrgPreferences.refileSettings().creating
820                guard creating != .no, let (parent, child) = RefileSettings.newNode(answer, in: targets) else { return commands.show("Invalid target location") }
821                let create = {
822                    switch session.createRefileChild(under: parent, title: child) {
823                    case .success(let target): if let message = session.refile(to: target, keep: keep) { commands.show(message) }
824                    case .failure(.message(let message)): commands.show(message)
825                    }
826                }
827                guard creating == .confirm else { return create() }
828                commands.ask(Prompt(key: "confirm", message: "Create new node \"\(child)\"?", choices: ["yes", "no"])) { reply in
829                    if reply == "yes" { create() }
830                }
831            }
832        case "app.refile.goto":
833            // `C-u C-c C-w`: the target heading, or the end of a file.
834            let targets = workspace.refileTargets(openPath: session.path, document: session.document)
835            commands.ask(Prompt(key: "refile", message: "Goto:", choices: targets.map(\.label))) { answer in
836                guard let answer, let target = targets.first(where: { $0.label == answer }) else { return }
837                commands.jump(path: target.path, offset: target.start ?? Int.max)
838            }
839        case "app.archive":
840            if let message = session.archive() { commands.show(message) }
841        case "app.table-import":
842            // `org-table-import`: a TSV, CSV or space-separated file becomes a table at point.
843            guard let editor = commands.editor else { return commands.show("No file is open") }
844            let panel = NSOpenPanel()
845            panel.allowedContentTypes = [.commaSeparatedText, .tabSeparatedText, .plainText]
846            guard panel.runModal() == .OK, let url = panel.url else { return }
847            guard let contents = try? String(contentsOf: url, encoding: .utf8) else { return commands.show("Can't read \(url.lastPathComponent)") }
848            editor.perform(ImportTable(contents: contents))
849        case "app.table-export":
850            // `org-table-export`: CSV for a .csv name, else TSV.
851            guard let editor = commands.editor else { return commands.show("No file is open") }
852            let context = editor.context()
853            guard ImportTable.exportText(context.text, at: context.caret, path: "") != nil else { return commands.show("No table at point") }
854            let panel = NSSavePanel()
855            panel.nameFieldStringValue = "table.csv"
856            guard panel.runModal() == .OK, let url = panel.url,
857                  let text = ImportTable.exportText(context.text, at: context.caret, path: url.path) else { return }
858            do {
859                try text.write(to: url, atomically: true, encoding: .utf8)
860                commands.show("Export done.")
861            } catch {
862                commands.show("File not written: \(error.localizedDescription)")
863            }
864        case "org.subtree.paste":
865            guard let text = NSPasteboard.general.string(forType: .string) else { return commands.show("The clipboard is empty") }
866            commands.editor?.perform(PasteSubtree(text: text))
867        case "org.link.insert":
868            commands.editor?.perform(InsertLink(stored: commands.storedLinks, file: session.path))
869        case "org.link.store":
870            guard let editor = commands.editor, let path = session.path else { return commands.show("No method for storing a link from this buffer") }
871            commands.storeLink(Links.store(in: editor.context(), path: Links.abbreviate(path, home: NSHomeDirectory())))
872        case "org.id.store-link":
873            guard let editor = commands.editor, let path = session.path else { return }
874            if case .commit = editor.perform(CreateID()),
875               let link = Links.storeID(in: editor.context(), fileName: (path as NSString).lastPathComponent) {
876                commands.storeLink(link)
877            }
878        case "app.agenda":
879            openWindow(id: "agenda")
880        case "app.clock.in":
881            clockIn(.caret)
882        case "app.clock.in-recent":
883            clockIn(.select)
884        case "app.clock.in-last":
885            clockIn(.last)
886        case let id where id.hasPrefix("app.clock.history."):
887            if let index = Int(id.dropFirst("app.clock.history.".count)), index < clock.history.count { clockIn(.task(clock.history[index])) }
888        case "app.clock.out":
889            commands.show(clock.clockOut(session))
890        case "app.clock.cancel":
891            commands.show(clock.clockOut(session, cancel: true))
892        case "app.clock.goto":
893            let found = clock.goto(session)
894            if let location = found.location { commands.jump(path: location.path, offset: location.offset) }
895            if let message = found.message { commands.show(message) }
896        case "app.clock.goto-recent":
897            Task {
898                let found = await clock.gotoRecent(session, ask: askClock)
899                if let location = found.location { commands.jump(path: location.path, offset: location.offset) }
900                if let message = found.message { commands.show(message) }
901            }
902        case "app.clock.default":
903            commands.show(clock.markDefault(session))
904        case "app.clock.resolve":
905            Task { report(await clock.resolveOpenClocks(session, paths: orgFiles, ask: askClock)) }
906        case "app.clock.report":
907            openWindow(id: "clock-report")
908        case "app.board":
909            openWindow(id: "board")
910        case "app.capture":
911            NSApp.activate()
912            openWindow(id: "capture")
913        case "app.revert":
914            // `:e`: the file as it is on disk; unsaved changes go to recovery.
915            guard session.path != nil else { return commands.show("No file is open") }
916            session.useDiskVersion()
917            commands.show("Reverted to the file on disk")
918        case "app.sync-conflicts":
919            guard session.path != nil else { return commands.show("No file is open") }
920            panel = .syncCopies(UUID())
921        case "app.recovery":
922            guard session.path != nil else { return commands.show("No file is open") }
923            panel = .recovery(UUID())
924        case "app.copy-rich-text":
925            copyRichText()
926        case "app.export-dialog":
927            guard let path = session.path else { return commands.show("No file is open") }
928            panel = .export(UUID(), URL(fileURLWithPath: path))
929        case let id where id.hasPrefix("app.export."):
930            export(String(id.dropFirst("app.export.".count)))
931        default:
932            if let editor = commands.editor { editor.run(id) } else { commands.show("No file is open") }
933        }
934    }
935
936    private var askClock: ClockModel.Ask { commands.askClock }
937
938    /// The files `org-resolve-clocks` looks through: the workspace's org files.
939    private var orgFiles: [String] { workspace.files.filter { $0.kind == .org }.map(\.path) }
940
941    private func clockIn(_ target: ClockModel.Target) {
942        Task { report(await clock.clockIn(session, target: target, paths: orgFiles, ask: askClock)) }
943    }
944
945    /// The last message of a clock command, and the clock to show for `j`.
946    private func report(_ outcome: ClockModel.Outcome) {
947        if let jump = outcome.jump { commands.jump(path: jump.path, offset: jump.offset) }
948        if let message = outcome.messages.last(where: { !$0.isEmpty }) { commands.show(message) }
949    }
950
951    private var errorShown: Binding<Bool> {
952        Binding(get: { workspace.lastError != nil || session.lastError != nil }, set: { _ in })
953    }
954}