Sources/Orgstar/ContentView.swift

22ff42f0ad29d59255e2ac93e0b3a28f66fca672
orgstar/Sources/Orgstar/ContentView.swift

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