Sources/Orgstar/ContentView.swift

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