Sources/Orgstar/ContentView.swift

8cc58a48ee7b1c77cc58f3feba6dc6a5fdb10ee0
orgstar/Sources/Orgstar/ContentView.swift

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