Sources/Orgstar/ContentView.swift

393d4d261fef7e5ac49bfe434dff59504a6b3544
orgstar/Sources/Orgstar/ContentView.swift

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