Sources/Orgstar/ContentView.swift

design-themes-widgets
orgstar/Sources/Orgstar/ContentView.swift history · blame · raw

1493 lines · 83257 bytes

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