Sources/Orgstar/ContentView.swift

5eef7a168632da902fdd0979d57258320e4fdfc2
orgstar/Sources/Orgstar/ContentView.swift history · blame · raw

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