Sources/Orgstar/ContentView.swift

1194 lines · 65246 bytes

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