Sources/Orgstar/ContentView.swift

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