Sources/Orgstar/ContentView.swift

60cc4d87d6d78c99bbe339580b8e42e59b0d3529
orgstar/Sources/Orgstar/ContentView.swift

1601 lines · 91624 bytes

   1import AppKit
   2import OrgApp
   3import OrgCore
   4import OrgEditorAppKit
   5import OrgPresentation
   6import OrgWorkspace
   7import OrgIndex
   8#if !APPSTORE
   9import OrgPrograms
  10#endif
  11import SwiftUI
  12import UniformTypeIdentifiers
  13import WidgetKit
  14
  15struct ContentView: View {
  16    let workspace: WorkspaceModel
  17    let session: DocumentSession
  18    @Bindable var commands: AppCommands
  19    let scheduler: ReminderScheduler?
  20    let clock: ClockModel
  21    @AppStorage("reminders") private var remindersEnabled = true
  22    @AppStorage("reminderLead") private var reminderLead = 12
  23    @AppStorage("clockIdleTime") private var clockIdleTime = 0
  24    @AppStorage("agendaSubfolders") private var agendaSubfolders = false
  25    @State private var reminderAgenda: AgendaModel?
  26    @State private var widgetAgenda: AgendaModel?
  27    @State private var trust = TrustStore()
  28    @State private var hotKey: GlobalHotKey?
  29    @State private var statusItem: ClockStatusItem?
  30    @AppStorage("globalCapture") private var globalCapture = true
  31    @AppStorage("menuBarItem") private var menuBarItem = false
  32    /// The sidebar shows the agenda in place of the files.
  33    @AppStorage("sidebarAgenda") private var sidebarAgenda = false
  34    /// Today's agenda for the menu bar item.
  35    @State private var menuToday: [AgendaSnapshot.Row] = []
  36    @State private var hour = 0
  37    @AppStorage("saveMode") private var saveMode = SaveMode.automatic
  38    @AppStorage("cryptBeforeSave") private var cryptBeforeSave = false
  39    @AppStorage("cryptTagMatcher") private var cryptTagMatcher = "crypt"
  40    @AppStorage("keymap") private var preset = KeymapPreset.emacs
  41    @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
  42    @State private var keymap = KeymapPreset.emacs.keymap
  43    @AppStorage("tagsColumn") private var tagsColumn = -77
  44    @AppStorage("headingAfterSubtree") private var headingAfterSubtree = false
  45    /// The welcome sheet has been shown once; it comes back only through the empty state.
  46    @AppStorage("welcomeShown") private var welcomeShown = false
  47    @AppStorage("splitLine") private var splitLine = false
  48    @AppStorage("alphabeticalLists") private var alphabeticalLists = true
  49    @AppStorage("fillColumn") private var fillColumn = 80
  50    @AppStorage("hiddenMarkers") private var hiddenMarkers = true
  51    @AppStorage("prettyEntities") private var prettyEntities = true
  52    @AppStorage("logDone") private var logDone = "nil"
  53    @AppStorage("logIntoDrawer") private var logIntoDrawer = ""
  54    @AppStorage("logReschedule") private var logReschedule = "nil"
  55    @AppStorage("logRedeadline") private var logRedeadline = "nil"
  56    @AppStorage("useSpeedCommands") private var useSpeedCommands = false
  57    @AppStorage("startupWithInlineImages") private var startupWithInlineImages = false
  58    @AppStorage("startupIndented") private var startupIndented = true
  59    @AppStorage("hideLeadingStars") private var hideLeadingStars = false
  60    @AppStorage("startupAlignAllTables") private var startupAlignAllTables = false
  61    @AppStorage("startupTruncated") private var startupTruncated = false
  62    @AppStorage("spellCheck") private var spellCheck = false
  63    @AppStorage("electricPair") private var electricPair = true
  64    @AppStorage("hideDrawerStartup") private var hideDrawerStartup = true
  65    @AppStorage("hideBlockStartup") private var hideBlockStartup = false
  66    @AppStorage("enforceTodoDependencies") private var enforceTodoDependencies = false
  67    @AppStorage("enforceTodoCheckboxDependencies") private var enforceTodoCheckboxDependencies = false
  68
  69    /// Bumped when user defaults change, so settings only config.toml has reach `options`.
  70    @State private var defaultsChanges = 0
  71    private var options: EditingOptions {
  72        _ = defaultsChanges
  73        var options = Preferences.options(
  74            tagsColumn: tagsColumn, headingAfterSubtree: headingAfterSubtree, splitLine: splitLine, alphabeticalLists: alphabeticalLists,
  75            fillColumn: fillColumn, hiddenMarkers: hiddenMarkers, prettyEntities: prettyEntities, logDone: logDone, logIntoDrawer: logIntoDrawer,
  76            hideDrawerStartup: hideDrawerStartup, hideBlockStartup: hideBlockStartup, logReschedule: logReschedule, logRedeadline: logRedeadline,
  77            useSpeedCommands: useSpeedCommands, startupWithInlineImages: startupWithInlineImages,
  78            startupIndented: startupIndented, hideLeadingStars: hideLeadingStars, startupAlignAllTables: startupAlignAllTables,
  79            startupTruncated: startupTruncated, spellCheck: spellCheck, electricPair: electricPair,
  80            enforceTodoDependencies: enforceTodoDependencies, enforceTodoCheckboxDependencies: enforceTodoCheckboxDependencies
  81        )
  82        // The agenda files, for clock tables over `agenda` scopes.
  83        options.agendaFiles = workspace.agendaFilePaths()
  84        options.denoteDirectories = DenoteNote.directories(roots: workspace.rootPaths)
  85        options.denoteSequenceScheme = OrgPreferences.denoteSequenceScheme()
  86        options.snippets = SnippetLibrary.shared.snippets
  87        options.timer = TimerModel.shared.timer
  88        return options
  89    }
  90    /// A block being edited apart (`org-edit-special`).
  91    @State private var blockEdit: BlockEditRequest?
  92    /// A sheet a command opened: column view or the export dialog.
  93    @State private var panel: Panel?
  94
  95    @State private var selectedFile: String?
  96    /// A file that isn't text, shown as a preview instead of the open document.
  97    @State private var previewPath: String?
  98    @AppStorage("outlineShown") private var orgOutlineShown = true
  99    @AppStorage("outlineWidth") private var outlineWidth = 220.0
 100    @AppStorage("backlinksShown") private var backlinksShown = true
 101    /// Lint File's panel is open; `lintRun` counts runs of the command.
 102    @State private var lintShown = false
 103    @State private var lintRun = 0
 104    @AppStorage("inspectorShown") private var inspectorShown = false
 105    @AppStorage("showMarkup") private var showMarkup = false
 106    @AppStorage("showLineNumbers") private var showLineNumbers = false
 107    @AppStorage("lineNumbersType") private var lineNumbersType = "t"
 108    @AppStorage("showHiddenFiles") private var showHiddenFiles = true
 109    @AppStorage("ignoredFolders") private var ignoredFolders = ScanRules.defaultIgnoredFolders.sorted().joined(separator: " ")
 110    @AppStorage("themeFont") private var themeFont = ""
 111    @AppStorage("themeBodyFont") private var themeBodyFont = ""
 112    @AppStorage("themeFontSize") private var themeFontSize = 13
 113    @AppStorage("themeLineSpacing") private var themeLineSpacing = 2
 114    @AppStorage("themeTextWidth") private var themeTextWidth = 0
 115    @AppStorage("themeHeadingStep") private var themeHeadingStep = 1
 116
 117    /// The theme's colors from config.toml with the type settings.
 118    private var theme: ThemeSpec {
 119        var spec = ConfigSync.shared.theme
 120        spec.font = themeFont
 121        spec.bodyFont = themeBodyFont
 122        spec.fontSize = themeFontSize
 123        spec.lineSpacing = themeLineSpacing
 124        spec.textWidth = themeTextWidth
 125        spec.headingSizeStep = themeHeadingStep
 126        return spec
 127    }
 128    /// The outline for a file that isn't org, off until asked for.
 129    @State private var plainOutlineShown = false
 130    @State private var showingImport = false
 131    @State private var showingTemplate = false
 132    /// Replace in Files, Rename Tag or Rename TODO Keyword, with the text to start from.
 133    @State private var replacing: (kind: ReplaceKind, initial: String)?
 134    @AppStorage("showTabBar") private var showTabBar = false
 135    /// This window's panes.
 136    @State private var window: WindowModel?
 137
 138    private var editorSettings: EditorSettings {
 139        EditorSettings(keymap: keymap, modal: preset.isModal, optionAsMeta: OptionAsMeta(rawValue: optionAsMeta), options: options, showMarkup: showMarkup, showLineNumbers: showLineNumbers,
 140                       lineNumbersType: LineNumbersType(rawValue: lineNumbersType) ?? .absolute, theme: theme)
 141    }
 142
 143    /// The pane that had the focus when a sheet opened, to act on when it closes.
 144    @State private var sheetTarget: EditorPane?
 145
 146    /// Puts the focus back on the pane a sheet was opened from.
 147    private func restoreSheetTarget() {
 148        guard let target = sheetTarget, session.panes.contains(where: { $0 === target }) else { return }
 149        sheetTarget = nil
 150        session.focused = target
 151        if let window = commands.store.window(of: target.id) { window.focused = target.id }
 152        if let path = target.path, let textView = commands.store.textView(for: target.id, path: path) {
 153            textView.window?.makeFirstResponder(textView)
 154            commands.editor = commands.store.editor(for: path)
 155        }
 156    }
 157
 158    /// The window holding the focused pane: this one, or an editor window.
 159    private var paneWindow: WindowModel? {
 160        commands.store.window(of: session.focused.id) ?? window
 161    }
 162
 163    /// Gives the focused pane's text view the keyboard, after a pane command moved the focus.
 164    private func focusPane(_ window: WindowModel) {
 165        window.activate(commands)
 166    }
 167    /// Carets of restored buffers, shown when each first shows.
 168    @State private var pendingCarets: [String: Int] = [:]
 169    @State private var query = ""
 170    @FocusState private var searchFocused: Bool
 171    @Environment(\.openWindow) private var openWindow
 172    @Environment(\.openSettings) private var openSettings
 173
 174    /// Whether the outline pane shows: remembered for org files, hidden by default for
 175    /// other files, and always shown while search results are up.
 176    private var outlineShown: Bool {
 177        !query.isEmpty || (previewPath == nil && (session.isOrg ? orgOutlineShown : plainOutlineShown))
 178    }
 179
 180    private func toggleOutline() {
 181        if session.isOrg { orgOutlineShown.toggle() } else { plainOutlineShown.toggle() }
 182    }
 183
 184    @ViewBuilder
 185    private var detail: some View {
 186        if let previewPath {
 187            FilePreview(path: previewPath)
 188        } else if !session.openPaths.isEmpty, let window {
 189            PaneLayoutView(layout: window.layout, window: window) { pane in
 190                PaneCell(pane: pane, window: window, session: session, commands: commands, showTabBar: showTabBar, onAppCommand: perform)
 191            }
 192            .safeAreaInset(edge: .bottom, spacing: 0) {
 193                VStack(spacing: 0) {
 194                    if lintShown {
 195                        LintPane(workspace: workspace, session: session, run: lintRun) { lintShown = false }
 196                            .frame(height: 190)
 197                        Divider()
 198                    }
 199                    CryptHoldBar(session: session) { commands.run("app.crypt.save") }
 200                    ModeLine(session: session, commands: commands)
 201                    EchoArea(commands: commands)
 202                }
 203            }
 204        } else {
 205            ContentUnavailableView {
 206                Label(noFolders ? "Add a folder of org files" : "Choose a file", systemImage: "doc.text")
 207            } description: {
 208                Text(noFolders ? "File ▸ Add Folder… (⇧⌘O)" : "Or press ⌘P to open one by name.")
 209            } actions: {
 210                if noFolders { Button("Get Started…") { commands.showingWelcome = true } }
 211            }
 212        }
 213    }
 214
 215    /// No folder to show: in the App Store build, also when none of them resolves, so the
 216    /// welcome sheet can ask for them again.
 217    private var noFolders: Bool {
 218        #if APPSTORE
 219        workspace.rootPaths.isEmpty
 220        #else
 221        workspace.roots.isEmpty
 222        #endif
 223    }
 224
 225    /// The toolbar, which View ▸ Customize Toolbar… can change.
 226    @ToolbarContentBuilder
 227    private var toolbarItems: some CustomizableToolbarContent {
 228        ToolbarItem(id: "outline", placement: .navigation) {
 229            Button(outlineShown ? "Hide Outline" : "Show Outline", systemImage: "list.bullet.indent") { toggleOutline() }
 230                .help(outlineShown ? "Hide the outline (⌥⌘O)" : "Show the outline (⌥⌘O)")
 231                .disabled(!query.isEmpty || previewPath != nil || session.path == nil)
 232        }
 233        ToolbarItem(id: "capture") {
 234            Button("Capture", systemImage: "square.and.pencil") { perform("app.capture") }
 235                .help("Capture a note (⇧⌘N)")
 236        }
 237        ToolbarItem(id: "agenda") {
 238            Button("Agenda", systemImage: "calendar") { perform("app.agenda") }
 239                .help("Open the agenda (⇧⌘A)")
 240        }
 241        ToolbarItem(id: "commands") {
 242            Button("Commands", systemImage: "command") { commands.showingPalette = true }
 243                .help("Find a command by name (⇧⌘P)")
 244        }
 245        ToolbarItem(id: "inspector") {
 246            Button(inspectorShown ? "Hide Inspector" : "Show Inspector", systemImage: "sidebar.trailing") { inspectorShown.toggle() }
 247                .help(inspectorShown ? "Hide the columns and clocked time (⌥⌘I)" : "Show the columns and clocked time (⌥⌘I)")
 248        }
 249        if workspace.isIndexing {
 250            ToolbarItem(id: "indexing") { ProgressView().controlSize(.small) }
 251                .customizationBehavior(.disabled)
 252        }
 253        if let running = clock.running {
 254            ToolbarItem(id: "clock") {
 255                TimelineView(.periodic(from: .now, by: 30)) { context in
 256                    Menu {
 257                        Button("Clock Out") { perform("app.clock.out") }
 258                        Button("Cancel Clock") { perform("app.clock.cancel") }
 259                        Button("Go to Clocked Entry") { perform("app.clock.goto") }
 260                        Divider()
 261                        Button("Clock In to Recent Entry…") { perform("app.clock.in-recent") }
 262                        Button("Go to Recent Clocked Entry…") { perform("app.clock.goto-recent") }
 263                        RecentClocks(clock: clock) { perform($0) }
 264                    } label: {
 265                        Label {
 266                            Text(verbatim: "\(running.heading) \(clockElapsed(running, now: context.date))").lineLimit(1)
 267                        } icon: {
 268                            Image(systemName: "clock")
 269                        }
 270                    }
 271                    .labelStyle(.titleAndIcon)
 272                }
 273                .help("Clocked in since \(running.startedAt.formatted(date: .omitted, time: .shortened))")
 274            }
 275        }
 276        if session.conflict != nil {
 277            ToolbarItem(id: "conflict") {
 278                Button("Conflict", systemImage: "exclamationmark.triangle") { commands.showingConflict = true }
 279                    .help("The file changed on disk, and the changes conflict with yours")
 280            }
 281            .customizationBehavior(.disabled)
 282        }
 283    }
 284
 285    private var main: some View {
 286        NavigationSplitView {
 287            Group {
 288                if sidebarAgenda {
 289                    AgendaSidebar(workspace: workspace, session: session, commands: commands, hour: hour, showsAgenda: $sidebarAgenda)
 290                } else {
 291                    Sidebar(workspace: workspace, session: session, selection: $selectedFile, showsAgenda: $sidebarAgenda) { commands.showingFolderPicker = true }
 292                }
 293            }
 294            .navigationSplitViewColumnWidth(min: 200, ideal: 260)
 295        } detail: {
 296            HStack(spacing: 0) {
 297                if outlineShown {
 298                    Group {
 299                        if query.isEmpty {
 300                            VStack(spacing: 0) {
 301                                OutlineColumn(session: session)
 302                                if backlinksShown, session.isOrg {
 303                                    Divider()
 304                                    BacklinksPane(workspace: workspace, session: session, commands: commands) { location in
 305                                        selectedFile = location.path
 306                                        session.show(location)
 307                                    }
 308                                }
 309                            }
 310                        } else {
 311                            SearchResults(results: Result { try workspace.search(query, overlay: workspace.overlay(session.openDocuments)) }) { location in
 312                                selectedFile = location.path
 313                                session.show(location)
 314                            }
 315                        }
 316                    }
 317                    .frame(width: CGFloat(outlineWidth))
 318                    PaneDivider(width: $outlineWidth, range: 160...400)
 319                }
 320                detail
 321                    .frame(maxWidth: .infinity)
 322                    .inspector(isPresented: $inspectorShown) {
 323                        InspectorPane(session: session, commands: commands, shown: inspectorShown)
 324                            .inspectorColumnWidth(min: 240, ideal: 340, max: 600)
 325                    }
 326            }
 327        }
 328        .navigationTitle(previewPath.map { ($0 as NSString).lastPathComponent } ?? session.path.map(session.bufferName) ?? "orgstar")
 329        .navigationSubtitle(session.isReadOnly ? "Read-only: not UTF-8" : "")
 330        .searchable(text: $query, placement: .toolbar, prompt: "Search notes")
 331        .searchFocused($searchFocused)
 332        .toolbar(id: "main") { toolbarItems }
 333        .onChange(of: session.path) { plainOutlineShown = false }
 334        .onChange(of: outlineShown, initial: true) { _, shown in commands.outlineShown = shown }
 335        .onChange(of: ScanRules(hiddenFiles: showHiddenFiles, ignoredFolders: Set(ignoredFolders.split(separator: " ").map(String.init))), initial: true) { _, rules in
 336            workspace.scanRules = rules
 337        }
 338        .onChange(of: selectedFile) { old, path in
 339            guard let path else { return }
 340            if !DocumentSession.isOrgPath(path), !FileTypes.isText(path) {
 341                previewPath = path
 342                return
 343            }
 344            previewPath = nil
 345            guard path != session.path else { return }
 346            session.open(path)
 347        }
 348        .onChange(of: session.path) {
 349            // Buffers switched by keys show in the sidebar too; a restored caret shows once.
 350            if let path = session.path, selectedFile != path { selectedFile = path }
 351            if let path = session.path, let caret = pendingCarets.removeValue(forKey: path) { session.reveal(caret) }
 352            saveBuffers()
 353            // Syncthing's conflict copies of the file.
 354            let copies = session.syncConflictCopies().count
 355            if copies > 0 { commands.show(String(localized: "\(copies) sync conflict copies of this file; Resolve Sync Conflicts compares them.")) }
 356        }
 357        .onChange(of: session.openPaths) { _, paths in
 358            saveBuffers()
 359            for path in commands.store.editors.keys where !paths.contains(path) { commands.store.releasePath(path) }
 360        }
 361        .onChange(of: editorSettings, initial: true) { _, settings in commands.editorSettings = settings }
 362        .onAppear {
 363            commands.externalHandler = runExternal
 364            commands.filesHandler = { attachActions.drop($0) }
 365            commands.imageHandler = { attachActions.yankImage($0, ext: $1) }
 366            #if APPSTORE
 367            commands.reach = { [workspace] in GrantAccess.reach($0, workspace: workspace) }
 368            #endif
 369            // `org-clock-out-when-done`, and the notification when the Effort runs out.
 370            clock.notifications = SystemReminderCenter.isAvailable ? SystemReminderCenter() : nil
 371            session.textChanged = { [weak session, weak clock, weak commands] path in
 372                guard let session, let clock, let message = clock.textChanged(path, session) else { return }
 373                commands?.show(message)
 374            }
 375            clock.remindAtEffort(session)
 376            commands.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] }
 377            commands.completionIndex = workspace.index
 378            commands.handoff.place = { [weak session, weak workspace] in workspace.flatMap { session?.handoffPlace(roots: $0.rootPaths) } }
 379            commands.continueHandoff = continueHandoff
 380            commands.mainWindowOpen = true
 381            commands.whatsNew = WhatsNew.pending(firstLaunch: noFolders && !welcomeShown)
 382            if noFolders, !welcomeShown {
 383                welcomeShown = true
 384                commands.showingWelcome = true
 385            }
 386            if let stale = window { commands.store.windows.removeAll { $0 === stale } }
 387            // The session's first pane the first time; a new one showing the focused buffer
 388            // when the window opens again.
 389            let pane: EditorPane
 390            if commands.store.window(of: session.panes[0].id) == nil, window == nil {
 391                pane = session.panes[0]
 392            } else {
 393                pane = session.makePane()
 394                if let path = session.focused.path { session.open(path, in: pane) }
 395            }
 396            let model = WindowModel(session: session, pane: pane)
 397            window = model
 398            commands.store.windows.insert(model, at: 0)
 399            model.focus(pane.id)
 400        }
 401        .onDisappear {
 402            commands.mainWindowOpen = false
 403            guard let model = window else { return }
 404            for id in model.layout.panes { commands.store.releasePane(id) }
 405            model.closeAll()
 406            commands.store.windows.removeAll { $0 === model }
 407            commands.editor = nil
 408        }
 409        .onChange(of: saveMode, initial: true) { _, mode in session.saveMode = mode }
 410        .modifier(CryptSettings(session: session, cryptBeforeSave: cryptBeforeSave, cryptTagMatcher: cryptTagMatcher) { path in
 411            panel = .crypt(UUID(), CryptRequest(mode: .openFile, path: path, offset: 0))
 412        })
 413        .onChange(of: options, initial: true) { _, options in session.options = options }
 414        .onAppear { TimerModel.shared.onDone = { [commands] in commands.show($0) } }
 415        .onReceive(NotificationCenter.default.publisher(for: UserDefaults.didChangeNotification)) { _ in defaultsChanges += 1 }
 416        .onChange(of: preset, initial: true) { loadKeymap() }
 417        .sheet(isPresented: $showingImport) { EmacsImportView(workspace: workspace) }
 418        .sheet(isPresented: $showingTemplate) {
 419            TemplateSheet(workspace: workspace, folder: session.path.map { ($0 as NSString).deletingLastPathComponent }) { selectedFile = $0 }
 420        }
 421        .sheet(item: Binding(get: { replacing?.kind }, set: { if $0 == nil { replacing = nil } })) { kind in
 422            ReplaceInFilesSheet(kind: kind, workspace: workspace, session: session, initial: replacing?.initial ?? "") { commands.show($0) }
 423        }
 424        .sheet(item: $panel) { panel in panelView(panel) }
 425        .sheet(item: Bindable(ProAccess.shared).paywall) { feature in
 426            #if APPSTORE
 427            StorePaywallSheet(feature: feature)
 428            #else
 429            ProPaywallSheet(feature: feature)
 430            #endif
 431        }
 432        .sheet(item: $blockEdit) { request in
 433            BlockEditorView(edit: request.edit) { content in
 434                blockEdit = nil
 435                guard let content else { return }
 436                commands.editor?.perform(ReplaceBlockLines(edit: request.edit, content: content))
 437            }
 438        }
 439        .sheet(isPresented: $commands.showingWelcome) {
 440            WelcomeView(workspace: workspace, chooseFolder: {
 441                // After the sheet closes, so the picker can present.
 442                DispatchQueue.main.async { commands.showingFolderPicker = true }
 443            }, open: { selectedFile = $0 })
 444        }
 445        .sheet(item: $commands.whatsNew) { WhatsNewView(notes: $0) }
 446        .sheet(isPresented: $commands.showingPalette) {
 447            PaletteView(commands: commands) { id in
 448                commands.showingPalette = false
 449                // After the sheet closes, so app commands can present their own, and in the
 450                // pane that had the focus when it opened: closing a sheet makes this window key.
 451                DispatchQueue.main.async {
 452                    restoreSheetTarget()
 453                    perform(id)
 454                }
 455            }
 456        }
 457        .sheet(isPresented: $commands.showingMessages) { MessagesView(messages: commands.messages) }
 458        .onChange(of: commands.showingPalette) { _, showing in if showing { sheetTarget = session.focused } }
 459        .onChange(of: commands.showingQuickOpen) { _, showing in if showing { sheetTarget = session.focused } }
 460        .onChange(of: session.conflict) { _, conflict in
 461            if conflict != nil { commands.showingConflict = true }
 462        }
 463        .onChange(of: commands.showingConflict) { _, showing in
 464            guard showing else { return }
 465            commands.showingConflict = false
 466            if session.conflict != nil { panel = .conflict(UUID()) }
 467        }
 468        .onChange(of: workspace.changedFile?.version) { fileChangedOnDisk() }
 469    }
 470
 471    /// A column view edit at the heading starting at `start` in the open file.
 472    private func runInColumnView(_ command: any OrgCommand, _ start: Int, _ answers: [String: String]) -> CommandStep {
 473        guard let path = session.path else { return .failed("No file is open") }
 474        return session.perform(command, path: path, at: start, expect: nil, answers: answers)
 475    }
 476
 477    /// An open file takes in what changed on disk, and a clock started or stopped in Emacs
 478    /// becomes the one shown.
 479    private func fileChangedOnDisk() {
 480        guard let path = workspace.changedFile?.path else { return }
 481        session.fileChanged(path)
 482        if path.hasSuffix(".org") { syncClock(paths: [path]) }
 483    }
 484
 485    /// Open clocks in `paths`: at launch and as folders load, the agenda files.
 486    private func syncClock(paths: [String]) {
 487        guard !workspace.files.isEmpty, let message = clock.sync(session, paths: paths) else { return }
 488        commands.show(message)
 489    }
 490
 491    var body: some View {
 492        main
 493        .task(id: workspace.files.count) { syncClock(paths: workspace.agendaFilePaths()) }
 494        .onChange(of: ClockMenuState(running: clock.running, history: clock.history, always: menuBarItem, today: menuToday), initial: true) { _, state in
 495            if statusItem == nil { statusItem = ClockStatusItem(run: { commands.run($0) }, jump: { commands.jump(path: $0, offset: $1) }) }
 496            statusItem?.update(state)
 497        }
 498        .task(id: menuBarItem) { if menuBarItem { await updateWidgets() } }
 499        .onChange(of: globalCapture, initial: true) { _, enabled in
 500            hotKey?.unregister()
 501            hotKey = enabled ? GlobalHotKey { perform("app.capture") } : nil
 502        }
 503        .onChange(of: commands.runRequest?.serial, initial: true) {
 504            if let id = commands.runRequest?.id { perform(id) }
 505        }
 506        .onChange(of: ConfigSync.shared.problems, initial: true) { _, problems in
 507            if let first = problems.first {
 508                commands.show(problems.count > 1 ? String(localized: "\(first) (and \(problems.count - 1) more)") : first)
 509            }
 510        }
 511        .onChange(of: ConfigSync.shared.changedFile?.serial) {
 512            // Named macros are commands keymap.toml can bind.
 513            if ["keymap.toml", NamedMacros.fileName].contains(ConfigSync.shared.changedFile?.name) { loadKeymap() }
 514        }
 515        .onChange(of: commands.jumpRequest?.id) {
 516            guard let request = commands.jumpRequest else { return }
 517            if request.path != session.path {
 518                session.open(request.path)
 519                selectedFile = request.path
 520            }
 521            session.reveal(request.offset)
 522        }
 523        // Handoff follows the focused file and its caret, and takes over again when the app does.
 524        .onChange(of: session.path, initial: true) { commands.handoff.changed() }
 525        .onChange(of: commands.selection) { commands.handoff.changed() }
 526        .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in commands.handoff.update() }
 527        .onChange(of: commands.focusSearch) { _, focus in
 528            if focus {
 529                searchFocused = true
 530                commands.focusSearch = false
 531            }
 532        }
 533        .fileImporter(isPresented: $commands.showingFolderPicker, allowedContentTypes: [.folder]) { result in
 534            guard case .success(let url) = result else { return }
 535            Task {
 536                do { try await workspace.addRoot(url) } catch {
 537                    workspace.showError(String(localized: "Couldn't Add Folder", comment: "Error alert title"), error.localizedDescription)
 538                }
 539            }
 540        }
 541        .sheet(isPresented: $commands.showingQuickOpen) {
 542            QuickOpenView(workspace: workspace) { entry in
 543                commands.showingQuickOpen = false
 544                DispatchQueue.main.async {
 545                    restoreSheetTarget()
 546                    selectedFile = entry.path
 547                    if selectedFile == entry.path { session.open(entry.path) }
 548                }
 549            }
 550        }
 551        .alert(errorTitle, isPresented: errorShown) {
 552            Button("OK") {
 553                workspace.lastError = nil
 554                session.lastError = nil
 555            }
 556        } message: {
 557            Text(workspace.lastError ?? session.lastError ?? "")
 558        }
 559        .task(id: ReminderKey(
 560            enabled: remindersEnabled, lead: reminderLead, subfolders: agendaSubfolders, hidden: HiddenFolders.shared.all, files: workspace.files.count,
 561            changed: workspace.changedFile?.version, edits: session.editVersion, hour: hour, theme: theme
 562        )) {
 563            // Once edits pause.
 564            try? await Task.sleep(for: .seconds(2))
 565            await updateReminders()
 566            await updateWidgets()
 567        }
 568        .task {
 569            while !Task.isCancelled {
 570                try? await Task.sleep(for: .seconds(3600))
 571                hour += 1
 572            }
 573        }
 574        // `org-resolve-clocks-if-idle`, checked every minute while a clock runs.
 575        .task(id: "\(clock.running?.start ?? "") \(clockIdleTime)") {
 576            guard clock.running != nil, clockIdleTime > 0 else { return }
 577            while !Task.isCancelled {
 578                try? await Task.sleep(for: .seconds(60))
 579                guard !Task.isCancelled, clock.running != nil, !clock.isResolving else { continue }
 580                let idle = ClockIdle.seconds()
 581                guard idle > Double(clockIdleTime * 60) else { continue }
 582                NSApp.requestUserAttention(.informationalRequest)
 583                report(await clock.resolveIdle(session, idleSince: Date().addingTimeInterval(-idle), ask: askClock))
 584            }
 585        }
 586        .task {
 587            #if !APPSTORE
 588            DevelopmentHooks.scheduleSnapshot()
 589            #endif
 590            pendingCarets = BufferRestore.restore(session)
 591            if let path = session.path, let caret = pendingCarets.removeValue(forKey: path) { session.reveal(caret) }
 592            // Files handed over at launch open after the restored buffers, and show.
 593            for path in AppDelegate.pendingOpens { session.open(path) }
 594            AppDelegate.pendingOpens = []
 595            for place in AppDelegate.pendingHandoffs { continueHandoff(place) }
 596            AppDelegate.pendingHandoffs = []
 597            #if APPSTORE
 598            for link in AppDelegate.pendingLinks { commands.handle(protocolURL: link) }
 599            AppDelegate.pendingLinks = []
 600            #else
 601            for link in AppDelegate.pendingLinks + [DevelopmentHooks.urlToOpen].compactMap({ $0 }) { commands.handle(protocolURL: link) }
 602            AppDelegate.pendingLinks = []
 603            if let path = DevelopmentHooks.fileToOpen { selectedFile = path }
 604            if let root = DevelopmentHooks.rootToAdd { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
 605            if let commandList = DevelopmentHooks.commandToRun {
 606                // The file opened above needs its editor first.
 607                for _ in 0..<20 where DevelopmentHooks.fileToOpen != nil && commands.editor == nil { try? await Task.sleep(for: .milliseconds(100)) }
 608                for command in commandList.split(separator: ",") { perform(String(command)) }
 609                for answer in DevelopmentHooks.answers {
 610                    for _ in 0..<20 where commands.prompt == nil { try? await Task.sleep(for: .milliseconds(100)) }
 611                    commands.answer(answer)
 612                }
 613            }
 614            if let id = DevelopmentHooks.windowToOpen {
 615                if id == "settings" { openSettings() } else { openWindow(id: id) }
 616            }
 617            #endif
 618            await workspace.refresh()
 619            workspace.startWatching()
 620        }
 621    }
 622
 623    /// The selection, or the whole file without one, on the clipboard as HTML, RTF and plain
 624    /// text, to paste formatted into mail and documents.
 625    private func copyRichText() {
 626        guard let path = session.path, let whole = session.document?.text, let editor = commands.editor else { return commands.show(String(localized: "No file is open")) }
 627        let defaults = Preferences.orgSettings.resolvingSetupFiles(in: whole, path: path, read: OrgSettings.readFile)
 628        let selection = editor.context().selection.first { !$0.isEmpty }
 629        let selected = selection.map { (whole as NSString).substring(with: NSRange($0)) }
 630        let url = URL(fileURLWithPath: path)
 631        let html = HTMLExport.page(
 632            selected ?? whole, fallbackTitle: url.deletingPathExtension().lastPathComponent, settings: defaults, path: path, bodyOnly: selected != nil,
 633            codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme), language: OrgPreferences.exportLanguage()
 634        )
 635        do {
 636            try RichTextExport.copy(html: html, directory: url.deletingLastPathComponent())
 637            commands.show(selected == nil ? String(localized: "Copied the file as rich text") : String(localized: "Copied the selection as rich text"))
 638        } catch {
 639            commands.show("\(error)")
 640        }
 641    }
 642
 643    /// Whether the caret is in a heading's subtree, which the export dialog can export alone.
 644    private var exportSubtreeAvailable: Bool {
 645        guard let text = session.document?.text, let caret = commands.editor?.context().caret else { return false }
 646        return ExportScope.subtree(text, at: caret) != nil
 647    }
 648
 649    /// Where an export goes by default: `#+EXPORT_FILE_NAME`, or the subtree's
 650    /// `EXPORT_FILE_NAME`, else beside the file, with `ext`.
 651    private func exportTarget(_ ext: String, subtree: Bool) -> URL {
 652        let path = session.path ?? ""
 653        let text = session.document?.text ?? ""
 654        let caret = subtree ? commands.editor?.context().caret : nil
 655        return ExportScope.output(for: URL(fileURLWithPath: path), name: ExportScope.fileName(text, subtreeAt: caret), extension: ext)
 656    }
 657
 658    /// Writes the export where `#+EXPORT_FILE_NAME` says or beside the file, as Emacs's export
 659    /// dispatcher does, or to `destination`, and opens it with `open`. `subtree` exports the
 660    /// subtree at the caret alone; `bodyOnly` leaves out the title and page wrapper.
 661    private func export(_ format: String, to destination: URL? = nil, open: Bool = false, subtree: Bool = false, bodyOnly: Bool = false) {
 662        if let feature = ProFeature.required(byExport: format), !ProAccess.shared.allows(feature) { return }
 663        if format == "icalendar-agenda" || format == "icalendar-combined" { return exportAgendaCalendars(combined: format == "icalendar-combined") }
 664        guard let path = session.path, var text = session.document?.text else {
 665            commands.show(String(localized: "No file is open"))
 666            return
 667        }
 668        guard readsIncludes(text, path: path) else { return }
 669        let url = URL(fileURLWithPath: path)
 670        let base = url.deletingPathExtension()
 671        let defaults = Preferences.orgSettings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
 672        let open = open || format == "html-open"
 673        let caret = commands.editor?.context().caret ?? 0
 674        let whole = text
 675        if subtree {
 676            guard let narrowed = ExportScope.subtree(text, at: caret, settings: defaults) else { return commands.show(String(localized: "Not in a subtree")) }
 677            text = narrowed
 678        }
 679        switch format {
 680        case "icalendar":
 681            let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
 682            guard let destination = destination ?? writable(ExportScope.output(for: url, name: name, extension: "ics")) else { return }
 683            do {
 684                let target = try ICalendarFiles.export(whole, path: path, settings: defaults, options: OrgPreferences.icalendarOptions(),
 685                                                       subtree: subtree ? caret : nil, destination: destination)
 686                commands.show(ExportSettings.exported(target.lastPathComponent, subtree: subtree, bodyOnly: bodyOnly))
 687                if open { NSWorkspace.shared.open(target) }
 688            } catch {
 689                commands.show(String(localized: "Can't export: \(error.localizedDescription)"))
 690            }
 691        case "html", "html-open", "markdown":
 692            let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
 693            guard let target = destination ?? writable(ExportScope.output(for: url, name: name, extension: format == "markdown" ? "md" : "html")) else { return }
 694            let content = format == "markdown"
 695                ? MarkdownExport.document(text, settings: defaults, path: path, bodyOnly: bodyOnly)
 696                : HTMLExport.page(
 697                    text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path, bodyOnly: bodyOnly,
 698                    codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme), language: OrgPreferences.exportLanguage()
 699                )
 700            do {
 701                try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
 702                try content.write(to: target, atomically: true, encoding: .utf8)
 703                commands.show(ExportSettings.exported(target.lastPathComponent, subtree: subtree, bodyOnly: bodyOnly))
 704                if open { NSWorkspace.shared.open(target) }
 705            } catch {
 706                commands.show(String(localized: "Can't write \(target.lastPathComponent): \(error.localizedDescription)"))
 707            }
 708        case "latex" where exportNative("LaTeX", extension: "tex", whole: whole, url: url, to: destination, open: open, subtree: subtree ? caret : nil, bodyOnly: bodyOnly, settings: defaults, export: {
 709            try LaTeXExport.document(text, settings: defaults, path: path, bodyOnly: bodyOnly, author: NSFullUserName(), language: OrgPreferences.exportLanguage(), file: true)
 710        }):
 711            break
 712        case "text" where exportNative("plain text", extension: "txt", whole: whole, url: url, to: destination, open: open, subtree: subtree ? caret : nil, bodyOnly: bodyOnly, settings: defaults, export: {
 713            try ASCIIExport.document(text, settings: defaults, path: path, bodyOnly: bodyOnly, author: NSFullUserName(), language: OrgPreferences.exportLanguage(), file: true)
 714        }):
 715            break
 716        case "odt":
 717            let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
 718            guard let target = destination ?? writable(ExportScope.output(for: url, name: name, extension: "odt")) else { return }
 719            // A missing image stops the export, so offer access to them first.
 720            _ = reach(ODTExport.imageFiles(text, settings: defaults, path: path).filter(WorkspaceModel.isThere))
 721            do {
 722                let data = try ODTExport.document(text, settings: defaults, path: path, author: NSFullUserName(), language: OrgPreferences.exportLanguage())
 723                try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
 724                try data.write(to: target, options: .atomic)
 725                commands.show(ExportSettings.exported(target.lastPathComponent, subtree: subtree, bodyOnly: bodyOnly))
 726                if open { NSWorkspace.shared.open(target) }
 727            } catch {
 728                commands.show(String(localized: "Can't export \(target.lastPathComponent): \(error.localizedDescription)"))
 729            }
 730        case "print-pdf", "docx", "rtf", "plain-text":
 731            let ext = ["print-pdf": "pdf", "plain-text": "txt"][format] ?? format
 732            let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
 733            guard let target = destination ?? writable(ExportScope.output(for: url, name: name, extension: ext)) else { return }
 734            let html = HTMLExport.page(
 735                text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path,
 736                codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme), language: OrgPreferences.exportLanguage()
 737            )
 738            let directory = url.deletingLastPathComponent()
 739            // Images that can't be read are left out, so offer access to them first.
 740            _ = reach(PDFExport.imageFiles(html, directory: directory).filter(WorkspaceModel.isThere))
 741            if format == "print-pdf" { commands.show(String(localized: "Exporting to PDF…")) }
 742            Task {
 743                do {
 744                    let data: Data
 745                    switch format {
 746                    case "print-pdf": data = try await PDFExport.pdf(html: html, directory: directory, options: OrgPreferences.pdfOptions())
 747                    case "docx": data = try RichTextExport.docx(html: html, directory: directory)
 748                    case "rtf": data = try RichTextExport.rtf(RichTextExport.attributed(html: html, directory: directory))
 749                    default: data = Data(RichTextExport.plain(try RichTextExport.attributed(html: html, directory: directory)).utf8)
 750                    }
 751                    try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
 752                    try data.write(to: target, options: .atomic)
 753                    commands.show(ExportSettings.exported(target.lastPathComponent, subtree: subtree, bodyOnly: bodyOnly))
 754                    if open { NSWorkspace.shared.open(target) }
 755                } catch {
 756                    commands.show(String(localized: "Can't export \(target.lastPathComponent): \(String(describing: error))"))
 757                }
 758            }
 759        default:
 760            #if !APPSTORE
 761            let functions = ["pdf": "org-latex-export-to-pdf", "latex": "org-latex-export-to-latex", "text": "org-ascii-export-to-ascii"]
 762            guard let function = functions[format] else { return }
 763            commands.show(String(localized: "Exporting with Emacs…"))
 764            commands.runInEmacs {
 765                do {
 766                    // Emacs narrows to the subtree and reads EXPORT_FILE_NAME itself.
 767                    let point = subtree ? (whole as NSString).substring(to: min(caret, (whole as NSString).length)).unicodeScalars.count + 1 : nil
 768                    var written = URL(fileURLWithPath: try await EmacsRunner.export(
 769                        text: whole, path: path, function: function, subtree: point, bodyOnly: bodyOnly
 770                    ))
 771                    if let destination, destination.standardizedFileURL != written.standardizedFileURL {
 772                        try? FileManager.default.removeItem(at: destination)
 773                        try FileManager.default.moveItem(at: written, to: destination)
 774                        written = destination
 775                    }
 776                    commands.show(ExportSettings.exported(written.lastPathComponent, subtree: subtree, bodyOnly: bodyOnly))
 777                    if open { NSWorkspace.shared.open(written) }
 778                } catch is CancellationError {
 779                    commands.show(String(localized: "Export canceled"))
 780                } catch {
 781                    commands.show("\(error)")
 782                }
 783            }
 784            #else
 785            let title = EditorCommands.all.first { $0.id == "app.export." + format }?.title
 786            commands.show(Self.unavailable(title ?? format))
 787            #endif
 788        }
 789    }
 790
 791    /// Writes what `export` makes, as ox does for `format`. False when the native export can't
 792    /// match Emacs and Emacs is installed to export instead; otherwise the reason is shown.
 793    private func exportNative(
 794        _ format: String, extension ext: String, whole: String, url: URL, to destination: URL?, open: Bool, subtree: Int?, bodyOnly: Bool, settings: OrgSettings,
 795        export: () throws -> String
 796    ) -> Bool {
 797        let content: String
 798        do {
 799            content = try export()
 800        } catch {
 801            #if !APPSTORE
 802            if EmacsRunner.executable() != nil { return false }
 803            #endif
 804            commands.show(String(localized: "Can't export to \(format): \(error.localizedDescription)"))
 805            return true
 806        }
 807        let name = ExportScope.fileName(whole, subtreeAt: subtree, settings: settings)
 808        guard let target = destination ?? writable(ExportScope.output(for: url, name: name, extension: ext)) else { return true }
 809        do {
 810            try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
 811            try content.write(to: target, atomically: true, encoding: .utf8)
 812            commands.show(ExportSettings.exported(target.lastPathComponent, subtree: subtree != nil, bodyOnly: bodyOnly))
 813            if open { NSWorkspace.shared.open(target) }
 814        } catch {
 815            commands.show(String(localized: "Can't write \(target.lastPathComponent): \(error.localizedDescription)"))
 816        }
 817        return true
 818    }
 819
 820    /// `url`; in the App Store build, when the sandbox keeps orgstar out of its folder, `url` once
 821    /// that folder is granted, or where a save panel puts it instead. Nil when canceled.
 822    private func writable(_ url: URL) -> URL? {
 823        #if APPSTORE
 824        guard let folder = workspace.foldersToGrant(for: [url.path]).first else { return url }
 825        let elsewhere = String(localized: "Save Elsewhere…", comment: "Button that asks where an export goes instead")
 826        switch GrantAccess.ask(folder, workspace: workspace, alternative: elsewhere) {
 827        case .granted: return url
 828        case .canceled: return nil
 829        case .alternative: break
 830        }
 831        let panel = NSSavePanel()
 832        panel.directoryURL = url.deletingLastPathComponent()
 833        panel.nameFieldStringValue = url.lastPathComponent
 834        panel.message = String(localized: "This file isn't in one of your folders. Choose where the export goes.", comment: "Save panel for an export outside the sidebar's folders")
 835        return panel.runModal() == .OK ? panel.url : nil
 836        #else
 837        return url
 838        #endif
 839    }
 840
 841    private func saveBuffers() {
 842        #if APPSTORE
 843        BufferRestore.save(session, workspace: workspace)
 844        #else
 845        BufferRestore.save(session)
 846        #endif
 847    }
 848
 849    /// In the App Store build, asks for the folders outside the sidebar's folders that `paths`
 850    /// need. False when one is still out of reach.
 851    private func reach(_ paths: @autoclosure () -> [String], directories: Bool = false) -> Bool {
 852        #if APPSTORE
 853        GrantAccess.reach(paths(), directories: directories, workspace: workspace)
 854        #else
 855        true
 856        #endif
 857    }
 858
 859    /// In the App Store build, offers access to the setup files and includes of `text` that
 860    /// can't be read. False, with a message, when an include still can't be read, rather than
 861    /// exporting it as an empty line.
 862    private func readsIncludes(_ text: String, path: String) -> Bool {
 863        #if APPSTORE
 864        let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
 865        var setupFiles: [String] = []
 866        _ = Preferences.orgSettings.resolvingSetupFiles(in: text, path: path) { file in
 867            let contents = OrgSettings.readFile(file)
 868            if contents == nil, WorkspaceModel.isThere(file) { setupFiles.append(file) }
 869            return contents
 870        }
 871        let includes = ExportPreprocess.unreadableIncludes(text, directory: directory).filter(WorkspaceModel.isThere)
 872        guard !(setupFiles + includes).isEmpty else { return true }
 873        _ = reach(setupFiles + includes)
 874        guard let unreadable = ExportPreprocess.unreadableIncludes(text, directory: directory).first else { return true }
 875        commands.show(String(localized: "Can't include \(OrgPaths.abbreviatingWithTilde(unreadable)).", comment: "Export stopped by an #+INCLUDE file that can't be read"))
 876        return false
 877        #else
 878        return true
 879        #endif
 880    }
 881
 882    /// Says a command doesn't run in this build.
 883    static func unavailable(_ title: String) -> String {
 884        String(localized: "\(CommandTitle.localized(title)) isn't available.", comment: "A command the Mac App Store build leaves out")
 885    }
 886
 887    /// `org-icalendar-export-agenda-files`, or with `combined`, `org-icalendar-combine-agenda-files`.
 888    private func exportAgendaCalendars(combined: Bool) {
 889        let paths = workspace.agendaFilePaths()
 890        guard reach(paths + (combined ? [OrgPreferences.icalendarCombinedFile()] : [])) else { return }
 891        let read = { (path: String) -> (text: String, settings: OrgSettings)? in
 892            guard let text = session.openDocuments.first(where: { $0.path == path })?.document.text ?? (try? String(contentsOfFile: path, encoding: .utf8)) else { return nil }
 893            return (text, Preferences.orgSettings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile))
 894        }
 895        do {
 896            let options = OrgPreferences.icalendarOptions()
 897            if combined {
 898                let url = try ICalendarFiles.combine(paths, to: OrgPreferences.icalendarCombinedFile(), options: options, read: read)
 899                commands.show(String(localized: "Exported \(paths.count) agenda files to \(url.lastPathComponent)"))
 900            } else {
 901                let written = try ICalendarFiles.exportEach(paths, options: options, read: read)
 902                commands.show(String(localized: "Exported \(written.count) agenda files to iCalendar"))
 903            }
 904        } catch {
 905            commands.show(String(localized: "Can't export: \(error.localizedDescription)"))
 906        }
 907    }
 908
 909    /// org-crypt's commands at the caret, through the passphrase sheet.
 910    private func crypt(_ id: String) {
 911        if id == "app.crypt.save" {
 912            guard let path = session.path, let hold = session.held[path] else { return }
 913            panel = .crypt(UUID(), CryptRequest.save(path, hold: hold))
 914            return
 915        }
 916        guard let editor = commands.editor, let path = session.path else { return commands.show(String(localized: "No file is open")) }
 917        let caret = editor.context().caret
 918        let text = editor.context().text
 919        switch id {
 920        case "app.crypt.forget-passphrase":
 921            session.forgetPassphrase(for: path)
 922            commands.show(String(localized: "Passphrase forgotten for \((path as NSString).lastPathComponent)"))
 923        case "app.crypt.encrypt-entries":
 924            panel = .crypt(UUID(), CryptRequest(mode: .encryptAll(tag: OrgPreferences.cryptTag()), path: path, offset: caret))
 925        default:
 926            guard OrgCrypt.heading(text, at: caret) != nil else { return commands.show(String(localized: "Before first headline")) }
 927            if id == "app.crypt.encrypt-entry" {
 928                guard OrgCrypt.encryptedRange(text, at: caret) == nil else { return commands.show(String(localized: "The entry is encrypted already")) }
 929                panel = .crypt(UUID(), CryptRequest(mode: .encrypt, path: path, offset: caret))
 930            } else {
 931                guard OrgCrypt.encryptedRange(text, at: caret) != nil else { return commands.show(String(localized: "Not an encrypted entry")) }
 932                panel = .crypt(UUID(), CryptRequest(mode: id == "app.crypt.open-entry" ? .open : .decryptInPlace, path: path, offset: caret))
 933            }
 934        }
 935    }
 936
 937    /// org-roam's daily notes and nodes.
 938    private var roamActions: RoamActions {
 939        var actions = RoamActions(
 940            session: session, roots: { [workspace] in workspace.rootPaths },
 941            nodes: { [workspace, session] in try workspace.nodes(overlay: workspace.overlay(session.openDocuments)) },
 942            show: { [commands] in commands.show($0) }, ask: { [commands] in commands.ask($0, reply: $1) },
 943            open: { [commands] path, offset in commands.jump(path: path, offset: offset) },
 944            insertLink: { [commands] link, title in
 945                guard let editor = commands.editor else { return commands.show(String(localized: "No file is open")) }
 946                let context = editor.context()
 947                let range = context.selection.first ?? context.caret..<context.caret
 948                let selected = (context.text as NSString).substring(with: NSRange(range))
 949                let text = Links.makeString(link, selected.isEmpty ? title : selected)
 950                let end = range.lowerBound + (text as NSString).length
 951                editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: [TextEdit(range: range, replacement: text)], selection: [end..<end])))
 952            },
 953            refresh: { [workspace] in Task { await workspace.refresh() } })
 954        #if APPSTORE
 955        actions.reachFolders = { [workspace] in GrantAccess.reach($0, directories: true, workspace: workspace) }
 956        #endif
 957        return actions
 958    }
 959
 960    /// org-attach's commands for the entry at the caret.
 961    private var attachActions: AttachActions {
 962        AttachActions(
 963            entry: { [commands, session] in
 964                guard let editor = commands.editor, let path = session.path else { return nil }
 965                let context = editor.context()
 966                return Attachments.Entry(text: context.text, offset: context.caret, path: path, options: context.options)
 967            },
 968            apply: { applyText($0, caret: $1) }, show: { [commands] in commands.show($0) }, ask: { [commands] in commands.ask($0, reply: $1) },
 969            storeLink: { [commands] in _ = StoredLink.add($0, to: &commands.storedLinks) },
 970            open: { [session, workspace, commands] file in
 971                if let message = LinkOpener.open(OrgLink(type: "file", path: file, raw: "file:" + file), session: session, workspace: workspace, ask: commands.ask) { commands.show(message) }
 972            },
 973            reveal: { NSWorkspace.shared.open(URL(fileURLWithPath: $0, isDirectory: true)) },
 974            pick: { method in
 975                let panel = NSOpenPanel()
 976                panel.canChooseDirectories = true
 977                panel.allowsMultipleSelection = true
 978                panel.message = "File to keep as an attachment"
 979                guard panel.runModal() == .OK else { return }
 980                #if APPSTORE
 981                // The sandbox can remove only files in the sidebar's folders, and links nothing.
 982                if method == .mv, let outside = panel.urls.first(where: { !workspace.contains($0) }) {
 983                    return commands.show(String(localized: "\(outside.lastPathComponent) isn't in one of your folders, so it can't be moved. Attach a copy instead.", comment: "Attach by moving a file from outside the sidebar's folders"))
 984                }
 985                guard method == .cp || method == .mv else { return }
 986                #endif
 987                attachActions.attach(panel.urls, method: method)
 988            })
 989    }
 990
 991    /// The sheet a panel shows.
 992    @ViewBuilder
 993    private func panelView(_ panel: Panel) -> some View {
 994        switch panel {
 995        case .columns(_, let view):
 996            ColumnViewSheet(view: view, run: runInColumnView, document: { session.document.map { ($0.text, $0.tree) } }) { offset in
 997                commands.editor?.reveal(offset)
 998            }
 999        case .export(_, let source):
1000            ExportSheet(source: source, inSubtree: exportSubtreeAvailable, target: exportTarget) { format, destination, open, subtree, bodyOnly in
1001                export(format, to: destination, open: open, subtree: subtree, bodyOnly: bodyOnly)
1002            }
1003        case .plot(_, let plot):
1004            PlotSheet(content: .chart(plot))
1005        case .plotImage(_, let url):
1006            PlotSheet(content: .image(url))
1007        case .shareSubtree(_, let share):
1008            ShareSubtreeSheet(share: share) { commands.show($0) }
1009        case .crypt(_, let request):
1010            CryptSheet(request: request, session: session, text: { session.document(of: request.path)?.text ?? "" }, apply: { applyText($0) }) { message in
1011                self.panel = nil
1012                // An encrypted file left closed: the sidebar shows the open file again.
1013                if case .openFile = request.mode, !session.isOpen(request.path) { selectedFile = session.path }
1014                if let message { commands.show(message) }
1015            }
1016        case .conflict:
1017            ConflictSheet(session: session)
1018        case .syncCopies:
1019            SyncConflictSheet(session: session) { commands.show($0) }
1020        case .recovery:
1021            HistorySheet(session: session) { commands.show($0) }
1022        }
1023    }
1024
1025    /// What Replace in Files starts with (the selection on one line) or a rename (the tag or
1026    /// keyword at the caret).
1027    private func replaceInitial(for kind: ReplaceKind) -> String {
1028        guard let editor = commands.editor else { return "" }
1029        let context = editor.context()
1030        if kind == .replace {
1031            let selected = context.selection.first.map { (context.text as NSString).substring(with: NSRange($0)) } ?? ""
1032            return selected.contains("\n") ? "" : selected
1033        }
1034        return kind.initial(text: context.text, caret: context.caret, keywords: context.tree.settings.todoKeywordNames)
1035    }
1036
1037    /// `new` in place of the buffer's text, as one edit, with the caret at `caret` or where it was.
1038    private func applyText(_ new: String, caret: Int? = nil) {
1039        guard let editor = commands.editor else { return }
1040        let context = editor.context()
1041        let caret = min(caret ?? context.caret, (new as NSString).length)
1042        editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
1043    }
1044
1045    /// `org-plot/gnuplot` for the table at the caret: through gnuplot when it's installed, as
1046    /// Emacs runs it, else drawn here; written to `file:` when the options name one, else shown.
1047    private func plotTable() {
1048        guard let editor = commands.editor, let path = session.path else { return commands.show(String(localized: "No file is open")) }
1049        let context = editor.context()
1050        let plot: TablePlot.Plot
1051        do { plot = try TablePlot.plot(context.text, at: context.caret) } catch { return commands.show("\(error)") }
1052        let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
1053        #if !APPSTORE
1054        if let gnuplot = PlotOutput.gnuplot {
1055            commands.show(String(localized: "Plotting with gnuplot…"))
1056            Task {
1057                do {
1058                    let image = try await PlotOutput.runGnuplot(plot, directory: directory, gnuplot: gnuplot)
1059                    if plot.options.file == nil { panel = .plotImage(UUID(), image) } else { plotWritten(image, editor: editor) }
1060                } catch {
1061                    commands.show("\(error)")
1062                }
1063            }
1064            return
1065        }
1066        #endif
1067        if let url = PlotOutput.file(plot, directory: directory) {
1068            guard reach([url.path]) else { return }
1069            do {
1070                try PlotOutput.write(plot, to: url)
1071                plotWritten(url, editor: editor, note: PlotOutput.note(plot))
1072            } catch {
1073                commands.show("\(error)")
1074            }
1075        } else {
1076            do { try PlotOutput.check(plot) } catch { return commands.show("\(error)") }
1077            panel = .plot(UUID(), plot)
1078            if let note = PlotOutput.note(plot) { commands.show(note) }
1079        }
1080    }
1081
1082    /// The image is where `file:` says; a link to it shows it again.
1083    private func plotWritten(_ url: URL, editor: OrgEditor, note: String? = nil) {
1084        commands.show(String(localized: "Plot written to \(url.lastPathComponent)") + (note.map { ". " + $0 } ?? ""))
1085        if editor.showsImages { editor.refreshImages() }
1086    }
1087
1088    /// `org-publish`, `org-publish-all`, `org-publish-current-file` and
1089    /// `org-publish-current-project`, with the projects in config.toml.
1090    private func publish(_ id: String) {
1091        let config = (try? String(contentsOf: UserConfig.file("config.toml"), encoding: .utf8)) ?? ""
1092        let loaded = Publish.projects(fromConfig: config, root: workspace.rootPaths.first)
1093        if let problem = loaded.problems.first { commands.show(problem) }
1094        guard !loaded.projects.isEmpty else { return commands.show(String(localized: "No [[publish]] projects in config.toml")) }
1095        let read = { (path: String) -> String? in
1096            session.openDocuments.first { $0.path == path }?.document.text ?? (try? String(contentsOfFile: path, encoding: .utf8))
1097        }
1098        let codeStyle = HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme)
1099        func run(_ chosen: [PublishProject], only: String? = nil) {
1100            // The chosen projects and their components read and write these folders.
1101            let involved = { loaded.projects.filter { project in chosen.contains { $0 == project || $0.components.contains(project.name) } } }
1102            guard reach(involved().flatMap { [$0.baseDirectory, $0.publishingDirectory] }, directories: true) else { return }
1103            do {
1104                let report = try Publish.publish(chosen, all: loaded.projects, only: only, read: read) { function, text, path, bodyOnly in
1105                    try Publish.export(function, text: text, path: path, bodyOnly: bodyOnly, settings: Preferences.orgSettings, codeStyle: codeStyle)
1106                }
1107                commands.show(report.skipped.isEmpty ? String(localized: "Published \(report.published.count) files")
1108                    : String(localized: "Published \(report.published.count) files, \(report.skipped.count) up to date"))
1109            } catch {
1110                commands.show("\(error)")
1111            }
1112        }
1113        let current = session.path.map { Publish.projects(containing: $0, in: loaded.projects) } ?? []
1114        switch id {
1115        case "app.publish.all":
1116            run(loaded.projects)
1117        case "app.publish.current-file":
1118            guard let path = session.path, !current.isEmpty else { return commands.show(String(localized: "File is not part of any known project")) }
1119            run([current[0]], only: path)
1120        case "app.publish.current-project":
1121            guard !current.isEmpty else { return commands.show(String(localized: "File is not part of any known project")) }
1122            run([current[0]])
1123        default:
1124            let names = loaded.projects.map(\.name)
1125            commands.ask(Prompt(key: "project", message: String(localized: "Publish project:"), choices: names)) { answer in
1126                guard let answer, let project = loaded.projects.first(where: { $0.name == answer }) else { return }
1127                run([project])
1128            }
1129        }
1130    }
1131
1132    /// Work a command hands to the platform: tables recalculated in Emacs.
1133    private func runExternal(_ request: ExternalRequest) {
1134        switch request {
1135        case .openLink(let link):
1136            if let message = LinkOpener.open(link, session: session, workspace: workspace, ask: commands.ask, elisp: runElispLink) { commands.show(message) }
1137            // `org-occur` for a regexp link, once the editor shows the file.
1138            if let regexp = Links.regexpSearch(link) {
1139                DispatchQueue.main.async { commands.editor?.perform(SparseTreeCommand(), answers: ["sparse": "/", "regexp": regexp]) }
1140            }
1141        case .tangle(let scope):
1142            guard ProAccess.shared.allows(.babel), reach(session.tangleFiles(scope)) else { return }
1143            commands.show(session.tangle(scope))
1144        case .agenda(let start, let days):
1145            commands.agendaRequest = (start, days)
1146            openWindow(id: "agenda")
1147        case .editBlock(let edit):
1148            blockEdit = BlockEditRequest(edit: edit)
1149        case .columnView(let view):
1150            panel = .columns(UUID(), view)
1151        #if APPSTORE
1152        case .emacsTable(_, _, _, let reason, _, let formula, let partial):
1153            // The fields written before the formula stay, as Emacs leaves them when a formula fails.
1154            if let partial { commands.editor?.perform(PrecomputedEdit(partial)) }
1155            if reason == TableBlocks.lockedReason {
1156                ProAccess.shared.allows(.babel)
1157                return
1158            }
1159            if let formula {
1160                commands.show(String(localized: "The table was recalculated up to \(formula), which can't be calculated here: \(TableReason.localized(reason)).", comment: "Table formulas orgstar calculated up to one it can't"))
1161            } else {
1162                commands.show(String(localized: "This table's formulas can't be calculated here: \(TableReason.localized(reason)).", comment: "Table formulas orgstar can't calculate"))
1163            }
1164        #else
1165        case .emacsTable(let table, let point, let form, let reason, let lisp, let formula, let partial):
1166            // Emacs runs the blocks `org-sbe` names without asking, so they need Babel, and
1167            // the question below each time.
1168            let blocks = reason == TableBlocks.lockedReason || session.document?.text.contains("org-sbe") == true
1169            if blocks, !ProAccess.shared.allows(.babel) {
1170                if let partial { commands.editor?.perform(PrecomputedEdit(partial)) }
1171                return
1172            }
1173            guard EmacsRunner.executable() != nil else {
1174                // Without Emacs this is the App Store build's case: keep the fields written so far.
1175                if let partial { commands.editor?.perform(PrecomputedEdit(partial)) }
1176                if let formula {
1177                    return commands.show(String(localized: "The table was recalculated up to \(formula), which can't be calculated here: \(TableReason.localized(reason)).", comment: "Table formulas orgstar calculated up to one it can't"))
1178                }
1179                return commands.show(String(localized: "This table's formulas can't be calculated here: \(TableReason.localized(reason)).", comment: "Table formulas orgstar can't calculate"))
1180            }
1181            let run = {
1182                commands.show(String(localized: "Recalculating in Emacs (\(TableReason.localized(reason)))…", comment: "Table formulas sent to Emacs, and why"))
1183                commands.runInEmacs { commands.show(await session.recalculateInEmacs(table: table, point: point, form: form)) }
1184            }
1185            guard lisp, let path = session.path, let text = session.document?.text else { return run() }
1186            let content = (text as NSString).substring(with: NSRange(location: table.lowerBound, length: min((text as NSString).length, table.upperBound + 2000) - table.lowerBound))
1187            if !blocks, trust.isTrusted(path: path, content: content) { return run() }
1188            let message = blocks ? String(localized: "This table's formulas run Lisp and source blocks. Run them? (yes, no)") : String(localized: "This table's formulas run Lisp. Run them? (yes, no, always)")
1189            commands.ask(Prompt(key: "confirm", message: message, choices: blocks ? ["yes", "no"] : ["yes", "no", "always"])) { answer in
1190                switch answer {
1191                case "always":
1192                    trust.trust(path: path, content: content)
1193                    run()
1194                case "yes": run()
1195                default: commands.show(String(localized: "Not recalculated"))
1196                }
1197            }
1198        #endif
1199        case .babel(let job):
1200            guard ProAccess.shared.allows(.babel) else { return }
1201            let run = {
1202                guard reach(session.resultFile(of: job).map { [$0] } ?? []) else { return }
1203                commands.show(String(localized: "Running \(job.language) block… (⌘. to cancel)"))
1204                session.startBabel(job) { commands.show($0) }
1205            }
1206            guard let path = session.path else { return }
1207            if !job.alwaysAsk, trust.isTrusted(path: path, content: job.blockText) { return run() }
1208            let choices = job.alwaysAsk ? ["yes", "no"] : ["yes", "no", "always"]
1209            commands.ask(Prompt(key: "confirm", message: String(localized: "Run this \(job.language) block? (\(choices.joined(separator: ", ")))"), choices: choices)) { answer in
1210                switch answer {
1211                case "always":
1212                    trust.trust(path: path, content: job.blockText)
1213                    run()
1214                case "yes": run()
1215                default: commands.show(String(localized: "Not run"))
1216                }
1217            }
1218        }
1219    }
1220
1221    /// Runs an `elisp:` link's form once trusted, asking as `org-link-elisp-confirm-function` does.
1222    private func runElispLink(_ form: String) {
1223        let run = { _ = Task { commands.show(await session.evaluateLink(form)) } }
1224        let content = "elisp:" + form
1225        if let path = session.path, trust.isTrusted(path: path, content: content) { return run() }
1226        let choices = session.path == nil ? ["yes", "no"] : ["yes", "no", "always"]
1227        commands.ask(Prompt(key: "confirm", message: String(localized: "Execute \(form) as Elisp? (\(choices.joined(separator: ", ")))"), choices: choices)) { answer in
1228            switch answer {
1229            case "always":
1230                if let path = session.path { trust.trust(path: path, content: content) }
1231                run()
1232            case "yes": run()
1233            default: commands.show(String(localized: "Not run"))
1234            }
1235        }
1236    }
1237
1238    private struct ReminderKey: Equatable {
1239        var enabled: Bool
1240        var lead: Int
1241        var subfolders: Bool
1242        /// The widgets leave out hidden folders.
1243        var hidden: Set<String>
1244        var files: Int
1245        var changed: Int?
1246        var edits: Int
1247        var hour: Int
1248        /// The widgets' colors.
1249        var theme: ThemeSpec
1250    }
1251
1252    /// Sets the notifications for the next week's timed entries, once edits pause.
1253    private func updateReminders() async {
1254        guard let scheduler else { return }
1255        guard remindersEnabled else {
1256            await scheduler.clear()
1257            return
1258        }
1259        guard !Task.isCancelled, !workspace.files.isEmpty else { return }
1260        let agenda = reminderAgenda ?? AgendaModel(workspace: workspace)
1261        reminderAgenda = agenda
1262        agenda.includeSubfolders = agendaSubfolders
1263        agenda.excludeArchives = OrgPreferences.agendaExcludeArchives()
1264        let open = session.openTexts
1265        let reminders = await agenda.reminders(open: open, lead: reminderLead)
1266        guard !Task.isCancelled else { return }
1267        await scheduler.reconcile(reminders)
1268    }
1269
1270    /// The desktop widgets' agenda and habits, written where the widget extension reads them,
1271    /// with the widgets reloaded when they changed; and today's agenda for the menu bar item.
1272    private func updateWidgets() async {
1273        let file = ProAccess.shared.isUnlocked ? AgendaSnapshot.file() : nil
1274        guard !Task.isCancelled, !workspace.files.isEmpty, file != nil || menuBarItem else { return }
1275        let days = widgetAgenda ?? AgendaModel(workspace: workspace)
1276        widgetAgenda = days
1277        days.mode = .agenda(span: AgendaSnapshot.dayCount, startOffset: 0)
1278        days.startOnWeekday = nil
1279        days.includeSubfolders = agendaSubfolders
1280        days.excludeArchives = OrgPreferences.agendaExcludeArchives()
1281        days.hiddenFolders = HiddenFolders.shared.all
1282        days.agendaFiles = OrgPreferences.agendaFiles()
1283        days.options = OrgPreferences.agendaOptions(days.options)
1284        days.options.logMode = false
1285        days.calendarEvents = ProAccess.shared.isUnlocked && OrgPreferences.calendarEvents() && CalendarEvents.isAuthorized ? CalendarAccess.events : nil
1286        days.calendarNames = OrgPreferences.calendarEventCalendars()
1287        days.reminderLists = ProAccess.shared.isUnlocked && OrgPreferences.agendaReminders() && ReminderLists.isAuthorized ? CalendarAccess.reminders : nil
1288        days.reminderListNames = OrgPreferences.agendaReminderLists()
1289        let open = session.openTexts
1290        await days.refresh(open: open)
1291        guard !Task.isCancelled else { return }
1292        let snapshot = AgendaSnapshot(groups: days.groups(), today: days.today, theme: theme, generated: Date())
1293        menuToday = snapshot.days.first.map { $0.overdue + $0.rows } ?? []
1294        guard let file else { return }
1295        if (try? HabitSnapshot(habits: await days.habits(open: open), theme: theme).write()) == true {
1296            WidgetCenter.shared.reloadTimelines(ofKind: "sh.krz.orgstar.habits")
1297        }
1298        if (try? snapshot.write(to: file)) == true { WidgetCenter.shared.reloadAllTimelines() }
1299    }
1300
1301    private func loadKeymap() {
1302        let loaded = KeymapLoader.load(preset, commands: Set(EditorCommands.all.map(\.id)))
1303        keymap = loaded.keymap
1304        commands.keymap = loaded.keymap
1305        commands.modal = preset.isModal
1306        if let first = loaded.problems.first {
1307            commands.show("keymap.toml: " + (loaded.problems.count > 1 ? String(localized: "\(first) (and \(loaded.problems.count - 1) more)") : first))
1308        }
1309    }
1310
1311    /// `SPC b b`: open buffers, most recent first, by name (with the folder when names repeat).
1312    private func switchBuffer() {
1313        let paths = session.recentPaths.dropFirst() + session.recentPaths.prefix(1)
1314        let labels = paths.map(session.bufferName)
1315        guard !labels.isEmpty else { return commands.show(String(localized: "No buffers are open")) }
1316        commands.ask(Prompt(key: "buffer", message: String(localized: "Switch to buffer:"), choices: labels)) { answer in
1317            guard let answer, let index = labels.firstIndex(of: answer) else { return }
1318            session.open(Array(paths)[index])
1319        }
1320    }
1321
1322    /// A file continued from another device, at the caret's heading or line there.
1323    private func continueHandoff(_ place: HandoffPlace) {
1324        let match = place.resolve(roots: workspace.rootPaths)
1325        guard case .file(let path) = match else { return commands.show(place.problem(match) ?? "") }
1326        let offset = session.text(of: path).map { place.offset(in: $0, settings: session.defaults) } ?? 0
1327        commands.jump(path: path, offset: offset)
1328    }
1329
1330    /// Runs a command from a key, the palette or the Org menu.
1331    private func perform(_ id: String) {
1332        if hiddenCommandIDs.contains(id) {
1333            if let replacement = AppStoreCommands.replacement(for: id) { return perform(replacement) }
1334            return commands.show(Self.unavailable(EditorCommands.all.first { $0.id == id }?.title ?? id))
1335        }
1336        if let feature = ProFeature.required(byCommand: id), !ProAccess.shared.allows(feature) { return }
1337        let orgOnly = ["app.refile", "app.refile.copy", "app.archive", "app.clock.in", "app.clock.default", "app.copy-rich-text", "app.export-subtree", "app.export-body-only", "app.share-subtree"].contains(id) || (id.hasPrefix("app.export.") && !id.hasPrefix("app.export.icalendar-")) || id.hasPrefix("org.")
1338        if orgOnly, !session.isOrg {
1339            commands.show(String(localized: "Not an org file"))
1340            return
1341        }
1342        switch id {
1343        case "app.save":
1344            if !session.save(), session.conflict != nil { commands.showingConflict = true }
1345        case "app.quit": NSApp.terminate(nil)
1346        case "app.save-all":
1347            if !session.saveAll(), session.conflict != nil { commands.showingConflict = true }
1348        case "app.buffer.switch": switchBuffer()
1349        case "app.buffer.next": session.cycle(1)
1350        case "app.buffer.previous": session.cycle(-1)
1351        case "app.buffer.last": session.showPrevious()
1352        case "app.buffer.kill":
1353            if let window = paneWindow, window.paneCount > 1 {
1354                window.closeTab(session.path, in: window.focusedPane, commands: commands)
1355            } else if let path = session.path {
1356                if UnsavedChanges.resolve(session) { session.kill(path) }
1357            } else {
1358                NSApp.keyWindow?.performClose(nil)
1359            }
1360        case "app.buffer.kill-others":
1361            let others = session.openPaths.filter { $0 != session.path }
1362            if UnsavedChanges.resolve(session, paths: others) { others.forEach(session.kill) }
1363        case "app.buffer.kill-all":
1364            let all = session.openPaths
1365            if UnsavedChanges.resolve(session, paths: all) { all.forEach(session.kill) }
1366        case "app.toggle-tab-bar": showTabBar.toggle()
1367        case "app.split-below": paneWindow?.split(.vertical)
1368        case "app.split-right": paneWindow?.split(.horizontal)
1369        case "app.pane-close":
1370            guard let window = paneWindow, window.paneCount > 1 else { return commands.show(String(localized: "This is the only pane.", comment: "Close Pane with one pane")) }
1371            commands.store.releasePane(window.focused)
1372            window.close(window.focused)
1373            focusPane(window)
1374        case "app.pane-only":
1375            guard let window = paneWindow else { return }
1376            for id in window.layout.panes where id != window.focused { commands.store.releasePane(id) }
1377            window.closeOthers()
1378            focusPane(window)
1379        case "app.pane-next":
1380            guard let window = paneWindow else { return }
1381            window.focusNext()
1382            focusPane(window)
1383        case "app.window-new": openWindow(id: "editor")
1384        case "app.babel.cancel":
1385            if session.isRunningBabel {
1386                session.cancelBabel()
1387            } else if let task = commands.emacsTask {
1388                task.cancel()
1389            } else {
1390                commands.show(String(localized: "Nothing is running"))
1391            }
1392        case "app.toggle-outline": toggleOutline()
1393        case "app.toggle-backlinks": backlinksShown.toggle()
1394        case "app.toggle-inspector": inspectorShown.toggle()
1395        case "app.toggle-markup": showMarkup.toggle()
1396        case "app.toggle-line-numbers": showLineNumbers.toggle()
1397        case "app.import-emacs": showingImport = true
1398        case "app.new-file-from-template": showingTemplate = true
1399        case "app.replace-in-files", "app.rename-tag", "app.rename-todo-keyword":
1400            replacing = ReplaceKind(command: id).map { ($0, replaceInitial(for: $0)) }
1401        case "app.edit-config": commands.jump(path: UserConfig.configFile.path, offset: 0)
1402        case "app.quick-open": commands.showingQuickOpen = true
1403        case "app.palette": commands.showingPalette = true
1404        case "app.messages": commands.showingMessages = true
1405        case "app.search": commands.focusSearch = true
1406        case "app.reload-keymap":
1407            loadKeymap()
1408            commands.show(String(localized: "Keymap reloaded"))
1409        case "app.refile", "app.refile.copy":
1410            let keep = id == "app.refile.copy"
1411            let targets = workspace.refileTargets(openPath: session.path, document: session.document)
1412            commands.ask(Prompt(key: "refile", message: keep ? String(localized: "Copy to:") : String(localized: "Refile to:"), choices: targets.map(\.label))) { answer in
1413                guard let answer else { return }
1414                if let target = targets.first(where: { $0.label == answer }) {
1415                    if let message = session.refile(to: target, keep: keep) { commands.show(message) }
1416                    return
1417                }
1418                // `org-refile-allow-creating-parent-nodes`: `parent/new` adds the heading first.
1419                let creating = OrgPreferences.refileSettings().creating
1420                guard creating != .no, let (parent, child) = RefileSettings.newNode(answer, in: targets) else { return commands.show(String(localized: "Invalid target location")) }
1421                let create = {
1422                    switch session.createRefileChild(under: parent, title: child) {
1423                    case .success(let target): if let message = session.refile(to: target, keep: keep) { commands.show(message) }
1424                    case .failure(.message(let message)): commands.show(message)
1425                    }
1426                }
1427                guard creating == .confirm else { return create() }
1428                commands.ask(Prompt(key: "confirm", message: String(localized: "Create new node \"\(child)\"?"), choices: ["yes", "no"])) { reply in
1429                    if reply == "yes" { create() }
1430                }
1431            }
1432        case "app.refile.goto":
1433            // `C-u C-c C-w`: the target heading, or the end of a file.
1434            let targets = workspace.refileTargets(openPath: session.path, document: session.document)
1435            commands.ask(Prompt(key: "refile", message: String(localized: "Goto:"), choices: targets.map(\.label))) { answer in
1436                guard let answer, let target = targets.first(where: { $0.label == answer }) else { return }
1437                commands.jump(path: target.path, offset: target.start ?? Int.max)
1438            }
1439        case "app.archive":
1440            guard reach(session.archiveFile().map { [$0] } ?? []) else { return }
1441            if let message = session.archive() { commands.show(message) }
1442        case "app.table-import":
1443            // `org-table-import`: a TSV, CSV or space-separated file becomes a table at point.
1444            guard let editor = commands.editor else { return commands.show(String(localized: "No file is open")) }
1445            let panel = NSOpenPanel()
1446            panel.allowedContentTypes = [.commaSeparatedText, .tabSeparatedText, .plainText]
1447            guard panel.runModal() == .OK, let url = panel.url else { return }
1448            guard let contents = try? String(contentsOf: url, encoding: .utf8) else { return commands.show(String(localized: "Can't read \(url.lastPathComponent)")) }
1449            editor.perform(ImportTable(contents: contents))
1450        case "app.table-export":
1451            // `org-table-export`: CSV for a .csv name, else TSV.
1452            guard let editor = commands.editor else { return commands.show(String(localized: "No file is open")) }
1453            let context = editor.context()
1454            guard ImportTable.exportText(context.text, at: context.caret, path: "") != nil else { return commands.show(String(localized: "No table at point")) }
1455            let panel = NSSavePanel()
1456            panel.nameFieldStringValue = "table.csv"
1457            guard panel.runModal() == .OK, let url = panel.url,
1458                  let text = ImportTable.exportText(context.text, at: context.caret, path: url.path) else { return }
1459            do {
1460                try text.write(to: url, atomically: true, encoding: .utf8)
1461                commands.show(String(localized: "Export done."))
1462            } catch {
1463                commands.show(String(localized: "File not written: \(error.localizedDescription)"))
1464            }
1465        case "org.subtree.paste":
1466            guard let text = NSPasteboard.general.string(forType: .string) else { return commands.show(String(localized: "The clipboard is empty")) }
1467            commands.editor?.perform(PasteSubtree(text: text))
1468        case "org.link.insert":
1469            commands.editor?.perform(InsertLink(stored: commands.storedLinks, file: session.path))
1470        case "org.link.store":
1471            guard let editor = commands.editor, let path = session.path else { return commands.show(String(localized: "No method for storing a link from this buffer")) }
1472            let context = editor.context()
1473            let denote = OrgPreferences.usesDenote() ? Links.storeDenote(in: context, path: path) : nil
1474            commands.storeLink(denote ?? Links.store(in: context, path: Links.abbreviate(path, home: OrgPaths.home)))
1475        case "org.id.store-link":
1476            guard let editor = commands.editor, let path = session.path else { return }
1477            if case .commit = editor.perform(CreateID()),
1478               let link = Links.storeID(in: editor.context(), fileName: (path as NSString).lastPathComponent) {
1479                commands.storeLink(link)
1480            }
1481        case "app.agenda":
1482            openWindow(id: "agenda")
1483        case "app.clock.in":
1484            clockIn(.caret)
1485        case "app.clock.in-recent":
1486            clockIn(.select)
1487        case "app.clock.in-last":
1488            clockIn(.last)
1489        case let id where id.hasPrefix("app.clock.history."):
1490            if let index = Int(id.dropFirst("app.clock.history.".count)), index < clock.history.count { clockIn(.task(clock.history[index])) }
1491        case "app.clock.out":
1492            commands.show(clock.clockOut(session))
1493        case "app.clock.cancel":
1494            commands.show(clock.clockOut(session, cancel: true))
1495        case "app.clock.goto":
1496            let found = clock.goto(session)
1497            if let location = found.location { commands.jump(path: location.path, offset: location.offset) }
1498            if let message = found.message { commands.show(message) }
1499        case "app.clock.goto-recent":
1500            Task {
1501                let found = await clock.gotoRecent(session, ask: askClock)
1502                if let location = found.location { commands.jump(path: location.path, offset: location.offset) }
1503                if let message = found.message { commands.show(message) }
1504            }
1505        case "app.clock.default":
1506            commands.show(clock.markDefault(session))
1507        case "app.clock.resolve":
1508            Task { report(await clock.resolveOpenClocks(session, paths: orgFiles, ask: askClock)) }
1509        case "app.clock.report":
1510            openWindow(id: "clock-report")
1511        case "app.board":
1512            openWindow(id: "board")
1513        case "app.node.graph":
1514            openWindow(id: "graph")
1515        case "app.sidebar-agenda":
1516            sidebarAgenda.toggle()
1517        case "app.capture":
1518            NSApp.activate()
1519            openWindow(id: "capture")
1520        case "app.revert":
1521            // `:e`: the file as it is on disk; unsaved changes go to recovery.
1522            guard session.path != nil else { return commands.show(String(localized: "No file is open")) }
1523            session.useDiskVersion()
1524            commands.show(String(localized: "Reverted to the file on disk"))
1525        case "app.sync-conflicts":
1526            guard session.path != nil else { return commands.show(String(localized: "No file is open")) }
1527            panel = .syncCopies(UUID())
1528        case "app.recovery":
1529            guard session.path != nil else { return commands.show(String(localized: "No file is open")) }
1530            panel = .recovery(UUID())
1531        case "app.lint":
1532            guard session.path != nil else { return commands.show(String(localized: "No file is open")) }
1533            guard FileLint.applies(to: session.path) else { return commands.show(String(localized: "Lint File works on Org files", comment: "Lint File in a file that isn't Org")) }
1534            lintShown = true
1535            lintRun += 1
1536        case "app.copy-rich-text":
1537            copyRichText()
1538        case "app.share-subtree":
1539            guard let path = session.path else { return commands.show(String(localized: "No file is open")) }
1540            guard let share = session.subtreeShare(path, at: session.caret) else { return commands.show(String(localized: "Not in a subtree")) }
1541            panel = .shareSubtree(UUID(), share)
1542        case "app.export-dialog":
1543            guard let path = session.path else { return commands.show(String(localized: "No file is open")) }
1544            panel = .export(UUID(), URL(fileURLWithPath: path))
1545        case "app.export-subtree", "app.export-body-only":
1546            guard let path = session.path else { return commands.show(String(localized: "No file is open")) }
1547            var settings = ExportSettings.saved(for: path)
1548            if id == "app.export-subtree" {
1549                settings.subtree.toggle()
1550                commands.show(settings.subtree ? String(localized: "Export commands: subtree at the caret") : String(localized: "Export commands: whole file"))
1551            } else {
1552                settings.bodyOnly.toggle()
1553                commands.show(settings.bodyOnly ? String(localized: "Export commands: body only") : String(localized: "Export commands: whole document"))
1554            }
1555            settings.save(for: path)
1556        case let id where id.hasPrefix("app.export."):
1557            let format = String(id.dropFirst("app.export.".count))
1558            guard let options = (session.path.map { ExportSettings.saved(for: $0) } ?? ExportSettings()).commandOptions(format) else {
1559                return commands.show(ExportSettings.noBodyOnly)
1560            }
1561            export(format, subtree: options.subtree, bodyOnly: options.bodyOnly)
1562        case let id where id.hasPrefix("app.publish"):
1563            publish(id)
1564        case "app.plot":
1565            plotTable()
1566        case let id where id.hasPrefix("app.crypt."):
1567            crypt(id)
1568        case let id where id.hasPrefix("app.attach."):
1569            guard reach(attachActions.entry().flatMap { Attachments.directory($0, noFSCheck: true) }.map { [$0] } ?? [], directories: true) else { return }
1570            attachActions.run(id)
1571        case let id where id.hasPrefix("app.dailies.") || id.hasPrefix("app.node."):
1572            roamActions.run(id)
1573        default:
1574            if let editor = commands.editor { editor.run(id) } else { commands.show(String(localized: "No file is open")) }
1575        }
1576    }
1577
1578    private var askClock: ClockModel.Ask { commands.askClock }
1579
1580    /// The files `org-resolve-clocks` looks through: the workspace's org files.
1581    private var orgFiles: [String] { workspace.files.filter { $0.kind == .org }.map(\.path) }
1582
1583    private func clockIn(_ target: ClockModel.Target) {
1584        Task { report(await clock.clockIn(session, target: target, paths: orgFiles, ask: askClock)) }
1585    }
1586
1587    /// The last message of a clock command, and the clock to show for `j`.
1588    private func report(_ outcome: ClockModel.Outcome) {
1589        if let jump = outcome.jump { commands.jump(path: jump.path, offset: jump.offset) }
1590        if let message = outcome.messages.last(where: { !$0.isEmpty }) { commands.show(message) }
1591    }
1592
1593    /// What failed, for the error alert's title.
1594    private var errorTitle: String {
1595        (workspace.lastError != nil ? workspace.lastErrorTitle : session.lastErrorTitle) ?? "orgstar"
1596    }
1597
1598    private var errorShown: Binding<Bool> {
1599        Binding(get: { workspace.lastError != nil || session.lastError != nil }, set: { _ in })
1600    }
1601}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form