Sources/Orgstar/ContentView.swift

06941b2cf25c6ccc1629723cd7951910ce15e67a
orgstar/Sources/Orgstar/ContentView.swift history · blame · raw

1140 lines · 61629 bytes

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