Sources/Orgstar/ContentView.swift

1191 lines · 65258 bytes

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