Sources/Orgstar/ContentView.swift

10c0d64a19b13f9e27044e7dd3edb2b708038aed
orgstar/Sources/Orgstar/ContentView.swift

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