Sources/Orgstar/ContentView.swift

1196 lines · 65421 bytes

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