Sources/Orgstar/ContentView.swift

9c8e4f9667c239dbcda0a122d127aa0620db4d35
orgstar/Sources/Orgstar/ContentView.swift

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