Sources/Orgstar/ContentView.swift

a35da9b28277882e9f4e9119a7e23c5ff696a21e
orgstar/Sources/Orgstar/ContentView.swift

1030 lines · 55943 bytes

   1import AppKit
   2import OrgApp
   3import OrgCore
   4import OrgEditorAppKit
   5import OrgPresentation
   6import OrgWorkspace
   7import OrgIndex
   8import SwiftUI
   9import UniformTypeIdentifiers
  10
  11struct ContentView: View {
  12    let workspace: WorkspaceModel
  13    let session: DocumentSession
  14    @Bindable var commands: AppCommands
  15    let scheduler: ReminderScheduler?
  16    let clock: ClockModel
  17    @AppStorage("reminders") private var remindersEnabled = true
  18    @AppStorage("reminderLead") private var reminderLead = 12
  19    @AppStorage("clockIdleTime") private var clockIdleTime = 0
  20    @AppStorage("agendaSubfolders") private var agendaSubfolders = false
  21    @State private var reminderAgenda: AgendaModel?
  22    @State private var trust = TrustStore()
  23    @State private var hotKey: GlobalHotKey?
  24    @State private var statusItem: ClockStatusItem?
  25    @AppStorage("globalCapture") private var globalCapture = true
  26    @State private var hour = 0
  27    @AppStorage("saveMode") private var saveMode = SaveMode.automatic
  28    @AppStorage("keymap") private var preset = KeymapPreset.emacs
  29    @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
  30    @State private var keymap = KeymapPreset.emacs.keymap
  31    @AppStorage("tagsColumn") private var tagsColumn = -77
  32    @AppStorage("headingAfterSubtree") private var headingAfterSubtree = true
  33    @AppStorage("splitLine") private var splitLine = false
  34    @AppStorage("alphabeticalLists") private var alphabeticalLists = true
  35    @AppStorage("fillColumn") private var fillColumn = 80
  36    @AppStorage("hiddenMarkers") private var hiddenMarkers = true
  37    @AppStorage("prettyEntities") private var prettyEntities = true
  38    @AppStorage("logDone") private var logDone = "nil"
  39    @AppStorage("logIntoDrawer") private var logIntoDrawer = ""
  40    @AppStorage("logReschedule") private var logReschedule = "nil"
  41    @AppStorage("logRedeadline") private var logRedeadline = "nil"
  42    @AppStorage("useSpeedCommands") private var useSpeedCommands = false
  43    @AppStorage("startupWithInlineImages") private var startupWithInlineImages = false
  44    @AppStorage("startupIndented") private var startupIndented = true
  45    @AppStorage("hideLeadingStars") private var hideLeadingStars = false
  46    @AppStorage("startupAlignAllTables") private var startupAlignAllTables = false
  47    @AppStorage("startupTruncated") private var startupTruncated = false
  48    @AppStorage("spellCheck") private var spellCheck = false
  49    @AppStorage("electricPair") private var electricPair = true
  50    @AppStorage("hideDrawerStartup") private var hideDrawerStartup = true
  51    @AppStorage("hideBlockStartup") private var hideBlockStartup = false
  52    @AppStorage("enforceTodoDependencies") private var enforceTodoDependencies = false
  53    @AppStorage("enforceTodoCheckboxDependencies") private var enforceTodoCheckboxDependencies = false
  54
  55    /// Bumped when user defaults change, so settings only config.toml has reach `options`.
  56    @State private var defaultsChanges = 0
  57    private var options: EditingOptions {
  58        _ = defaultsChanges
  59        var options = Preferences.options(
  60            tagsColumn: tagsColumn, headingAfterSubtree: headingAfterSubtree, splitLine: splitLine, alphabeticalLists: alphabeticalLists,
  61            fillColumn: fillColumn, hiddenMarkers: hiddenMarkers, prettyEntities: prettyEntities, logDone: logDone, logIntoDrawer: logIntoDrawer,
  62            hideDrawerStartup: hideDrawerStartup, hideBlockStartup: hideBlockStartup, logReschedule: logReschedule, logRedeadline: logRedeadline,
  63            useSpeedCommands: useSpeedCommands, startupWithInlineImages: startupWithInlineImages,
  64            startupIndented: startupIndented, hideLeadingStars: hideLeadingStars, startupAlignAllTables: startupAlignAllTables,
  65            startupTruncated: startupTruncated, spellCheck: spellCheck, electricPair: electricPair,
  66            enforceTodoDependencies: enforceTodoDependencies, enforceTodoCheckboxDependencies: enforceTodoCheckboxDependencies
  67        )
  68        // The agenda files, for clock tables over `agenda` scopes.
  69        options.agendaFiles = workspace.agendaFilePaths()
  70        return options
  71    }
  72    /// A block being edited apart (`org-edit-special`).
  73    @State private var blockEdit: BlockEditRequest?
  74    /// A sheet a command opened: column view or the export dialog.
  75    @State private var panel: Panel?
  76
  77    @State private var selectedFile: String?
  78    /// A file that isn't text, shown as a preview instead of the open document.
  79    @State private var previewPath: String?
  80    @AppStorage("outlineShown") private var orgOutlineShown = true
  81    @AppStorage("outlineWidth") private var outlineWidth = 220.0
  82    @AppStorage("backlinksShown") private var backlinksShown = true
  83    @AppStorage("inspectorShown") private var inspectorShown = false
  84    @AppStorage("showMarkup") private var showMarkup = false
  85    @AppStorage("showLineNumbers") private var showLineNumbers = true
  86    @AppStorage("showHiddenFiles") private var showHiddenFiles = true
  87    @AppStorage("ignoredFolders") private var ignoredFolders = ScanRules.defaultIgnoredFolders.sorted().joined(separator: " ")
  88    @AppStorage("themeFont") private var themeFont = ""
  89    @AppStorage("themeFontSize") private var themeFontSize = 13
  90    @AppStorage("themeLineSpacing") private var themeLineSpacing = 2
  91    @AppStorage("themeHeadingStep") private var themeHeadingStep = 1
  92
  93    /// The theme's colors from config.toml with the type settings.
  94    private var theme: ThemeSpec {
  95        var spec = ConfigSync.shared.theme
  96        spec.font = themeFont
  97        spec.fontSize = themeFontSize
  98        spec.lineSpacing = themeLineSpacing
  99        spec.headingSizeStep = themeHeadingStep
 100        return spec
 101    }
 102    /// The outline for a file that isn't org, off until asked for.
 103    @State private var plainOutlineShown = false
 104    @State private var showingImport = false
 105    @AppStorage("showTabBar") private var showTabBar = false
 106    /// This window's panes.
 107    @State private var window: WindowModel?
 108
 109    private var editorSettings: EditorSettings {
 110        EditorSettings(keymap: keymap, modal: preset.isModal, optionAsMeta: OptionAsMeta(rawValue: optionAsMeta), options: options, showMarkup: showMarkup, showLineNumbers: showLineNumbers, theme: theme)
 111    }
 112
 113    /// The pane that had the focus when a sheet opened, to act on when it closes.
 114    @State private var sheetTarget: EditorPane?
 115
 116    /// Puts the focus back on the pane a sheet was opened from.
 117    private func restoreSheetTarget() {
 118        guard let target = sheetTarget, session.panes.contains(where: { $0 === target }) else { return }
 119        sheetTarget = nil
 120        session.focused = target
 121        if let window = commands.store.window(of: target.id) { window.focused = target.id }
 122        if let path = target.path, let textView = commands.store.textView(for: target.id, path: path) {
 123            textView.window?.makeFirstResponder(textView)
 124            commands.editor = commands.store.editor(for: path)
 125        }
 126    }
 127
 128    /// The window holding the focused pane: this one, or an editor window.
 129    private var paneWindow: WindowModel? {
 130        commands.store.window(of: session.focused.id) ?? window
 131    }
 132
 133    /// Gives the focused pane's text view the keyboard, after a pane command moved the focus.
 134    private func focusPane(_ window: WindowModel) {
 135        let pane = window.focusedPane
 136        session.focused = pane
 137        if let path = pane.path, let textView = commands.store.textView(for: pane.id, path: path) {
 138            textView.window?.makeFirstResponder(textView)
 139            commands.editor = commands.store.editor(for: path)
 140        } else {
 141            commands.editor = nil
 142        }
 143    }
 144    /// Carets of restored buffers, shown when each first shows.
 145    @State private var pendingCarets: [String: Int] = [:]
 146    @State private var query = ""
 147    @FocusState private var searchFocused: Bool
 148    @Environment(\.openWindow) private var openWindow
 149    @Environment(\.openSettings) private var openSettings
 150
 151    /// Whether the outline pane shows: remembered for org files, hidden by default for
 152    /// other files, and always shown while search results are up.
 153    private var outlineShown: Bool {
 154        !query.isEmpty || (previewPath == nil && (session.isOrg ? orgOutlineShown : plainOutlineShown))
 155    }
 156
 157    private func toggleOutline() {
 158        if session.isOrg { orgOutlineShown.toggle() } else { plainOutlineShown.toggle() }
 159    }
 160
 161    @ViewBuilder
 162    private var detail: some View {
 163        if let previewPath {
 164            FilePreview(path: previewPath)
 165        } else if !session.openPaths.isEmpty, let window {
 166            PaneLayoutView(layout: window.layout, window: window) { pane in
 167                PaneCell(pane: pane, window: window, session: session, commands: commands, showTabBar: showTabBar, onAppCommand: perform)
 168            }
 169            .safeAreaInset(edge: .bottom, spacing: 0) {
 170                VStack(spacing: 0) {
 171                    ModeLine(session: session, commands: commands, clock: clock, perform: perform)
 172                    EchoArea(commands: commands)
 173                }
 174            }
 175        } else {
 176            ContentUnavailableView(
 177                workspace.roots.isEmpty ? "Add a folder of org files" : "Choose a file",
 178                systemImage: "doc.text",
 179                description: Text(workspace.roots.isEmpty ? "File ▸ Add Folder… (⇧⌘O)" : "Or press ⌘P to open one by name.")
 180            )
 181        }
 182    }
 183
 184    @ToolbarContentBuilder
 185    private var toolbarItems: some ToolbarContent {
 186        ToolbarItem(placement: .navigation) {
 187            Button(outlineShown ? "Hide Outline" : "Show Outline", systemImage: "list.bullet.indent") { toggleOutline() }
 188                .help(outlineShown ? "Hide the outline (⌥⌘O)" : "Show the outline (⌥⌘O)")
 189                .disabled(!query.isEmpty || previewPath != nil || session.path == nil)
 190        }
 191        if workspace.isIndexing {
 192            ToolbarItem { ProgressView().controlSize(.small) }
 193        }
 194        if let running = clock.running {
 195            ToolbarItem {
 196                Menu {
 197                    Button("Clock Out") { perform("app.clock.out") }
 198                    Button("Cancel Clock") { perform("app.clock.cancel") }
 199                    Button("Go to Clocked Entry") { perform("app.clock.goto") }
 200                    Divider()
 201                    Button("Clock In to Recent Entry…") { perform("app.clock.in-recent") }
 202                    Button("Go to Recent Clocked Entry…") { perform("app.clock.goto-recent") }
 203                    RecentClocks(clock: clock) { perform($0) }
 204                } label: {
 205                    TimelineView(.periodic(from: .now, by: 30)) { context in
 206                        Text("⏱ \(running.heading) \(clockElapsed(running, now: context.date))").lineLimit(1)
 207                    }
 208                }
 209                .help("Clocked in since \(running.startedAt.formatted(date: .omitted, time: .shortened))")
 210            }
 211        }
 212        if session.conflict != nil {
 213            ToolbarItem {
 214                Button("Conflict", systemImage: "exclamationmark.triangle") { commands.showingConflict = true }
 215                    .help("The file changed on disk, and the changes conflict with yours")
 216            }
 217        }
 218    }
 219
 220    private var main: some View {
 221        NavigationSplitView {
 222            Sidebar(workspace: workspace, session: session, selection: $selectedFile) { commands.showingFolderPicker = true }
 223                .navigationSplitViewColumnWidth(min: 200, ideal: 260)
 224        } detail: {
 225            HStack(spacing: 0) {
 226                if outlineShown {
 227                    Group {
 228                        if query.isEmpty {
 229                            VStack(spacing: 0) {
 230                                OutlineColumn(session: session)
 231                                if backlinksShown, session.isOrg {
 232                                    Divider()
 233                                    BacklinksPane(workspace: workspace, session: session, commands: commands) { location in
 234                                        selectedFile = location.path
 235                                        session.show(location)
 236                                    }
 237                                    .frame(height: 200)
 238                                }
 239                            }
 240                        } else {
 241                            SearchResults(results: workspace.search(query, overlay: workspace.overlay(session.openDocuments))) { location in
 242                                selectedFile = location.path
 243                                session.show(location)
 244                            }
 245                        }
 246                    }
 247                    .frame(width: CGFloat(outlineWidth))
 248                    PaneDivider(width: $outlineWidth, range: 160...400)
 249                }
 250                detail
 251                    .frame(maxWidth: .infinity)
 252                    .inspector(isPresented: $inspectorShown) {
 253                        InspectorPane(session: session, commands: commands)
 254                            .inspectorColumnWidth(min: 240, ideal: 340, max: 600)
 255                    }
 256            }
 257        }
 258        .navigationTitle(previewPath.map { ($0 as NSString).lastPathComponent } ?? session.path.map(session.bufferName) ?? "orgstar")
 259        .navigationSubtitle(session.isReadOnly ? "Read-only: not UTF-8" : "")
 260        .searchable(text: $query, placement: .toolbar, prompt: "Search notes")
 261        .searchFocused($searchFocused)
 262        .toolbar { toolbarItems }
 263        .onChange(of: session.path) { plainOutlineShown = false }
 264        .onChange(of: ScanRules(hiddenFiles: showHiddenFiles, ignoredFolders: Set(ignoredFolders.split(separator: " ").map(String.init))), initial: true) { _, rules in
 265            workspace.scanRules = rules
 266        }
 267        .onChange(of: selectedFile) { old, path in
 268            guard let path else { return }
 269            if !DocumentSession.isOrgPath(path), !FileTypes.isText(path) {
 270                previewPath = path
 271                return
 272            }
 273            previewPath = nil
 274            guard path != session.path else { return }
 275            session.open(path)
 276        }
 277        .onChange(of: session.path) {
 278            // Buffers switched by keys show in the sidebar too; a restored caret shows once.
 279            if let path = session.path, selectedFile != path { selectedFile = path }
 280            if let path = session.path, let caret = pendingCarets.removeValue(forKey: path) { session.reveal(caret) }
 281            BufferRestore.save(session)
 282            // Syncthing's conflict copies of the file.
 283            let copies = session.syncConflictCopies().count
 284            if copies > 0 { commands.show("\(copies) sync conflict \(copies == 1 ? "copy" : "copies") of this file; Resolve Sync Conflicts compares them.") }
 285        }
 286        .onChange(of: session.openPaths) { _, paths in
 287            BufferRestore.save(session)
 288            for path in commands.store.editors.keys where !paths.contains(path) { commands.store.releasePath(path) }
 289        }
 290        .onChange(of: editorSettings, initial: true) { _, settings in commands.editorSettings = settings }
 291        .onAppear {
 292            commands.externalHandler = runExternal
 293            // `org-clock-out-when-done`, and the notification when the Effort runs out.
 294            clock.notifications = SystemReminderCenter.isAvailable ? SystemReminderCenter() : nil
 295            session.textChanged = { [weak session, weak clock, weak commands] path in
 296                guard let session, let clock, let message = clock.textChanged(path, session) else { return }
 297                commands?.show(message)
 298            }
 299            clock.remindAtEffort(session)
 300            commands.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] }
 301            commands.mainWindowOpen = true
 302            if let stale = window { commands.store.windows.removeAll { $0 === stale } }
 303            // The session's first pane the first time; a new one showing the focused buffer
 304            // when the window opens again.
 305            let pane: EditorPane
 306            if commands.store.window(of: session.panes[0].id) == nil, window == nil {
 307                pane = session.panes[0]
 308            } else {
 309                pane = session.makePane()
 310                if let path = session.focused.path { session.open(path, in: pane) }
 311            }
 312            let model = WindowModel(session: session, pane: pane)
 313            window = model
 314            commands.store.windows.insert(model, at: 0)
 315            model.focus(pane.id)
 316        }
 317        .onDisappear {
 318            commands.mainWindowOpen = false
 319            guard let model = window else { return }
 320            for id in model.layout.panes { commands.store.releasePane(id) }
 321            model.closeAll()
 322            commands.store.windows.removeAll { $0 === model }
 323            commands.editor = nil
 324        }
 325        .onChange(of: saveMode, initial: true) { _, mode in session.saveMode = mode }
 326        .onChange(of: options, initial: true) { _, options in session.options = options }
 327        .onReceive(NotificationCenter.default.publisher(for: UserDefaults.didChangeNotification)) { _ in defaultsChanges += 1 }
 328        .onChange(of: preset, initial: true) { loadKeymap() }
 329        .sheet(isPresented: $showingImport) { EmacsImportView(workspace: workspace) }
 330        .sheet(item: $panel) { panel in
 331            switch panel {
 332            case .columns(_, let view):
 333                ColumnViewSheet(view: view, run: runInColumnView, document: { session.document.map { ($0.text, $0.tree) } }) { offset in
 334                    commands.editor?.reveal(offset)
 335                }
 336            case .export(_, let source):
 337                ExportSheet(source: source, inSubtree: exportSubtreeAvailable, target: exportTarget) { format, destination, open, subtree, bodyOnly in
 338                    export(format, to: destination, open: open, subtree: subtree, bodyOnly: bodyOnly)
 339                }
 340            case .conflict:
 341                ConflictSheet(session: session)
 342            case .syncCopies:
 343                SyncConflictSheet(session: session) { commands.show($0) }
 344            case .recovery:
 345                RecoverySheet(session: session) { commands.show($0) }
 346            }
 347        }
 348        .sheet(item: $blockEdit) { request in
 349            BlockEditorView(edit: request.edit) { content in
 350                blockEdit = nil
 351                guard let content else { return }
 352                commands.editor?.perform(ReplaceBlockLines(edit: request.edit, content: content))
 353            }
 354        }
 355        .sheet(isPresented: $commands.showingPalette) {
 356            PaletteView(commands: commands) { id in
 357                commands.showingPalette = false
 358                // After the sheet closes, so app commands can present their own, and in the
 359                // pane that had the focus when it opened: closing a sheet makes this window key.
 360                DispatchQueue.main.async {
 361                    restoreSheetTarget()
 362                    perform(id)
 363                }
 364            }
 365        }
 366        .onChange(of: commands.showingPalette) { _, showing in if showing { sheetTarget = session.focused } }
 367        .onChange(of: commands.showingQuickOpen) { _, showing in if showing { sheetTarget = session.focused } }
 368        .onChange(of: session.conflict) { _, conflict in
 369            if conflict != nil { commands.showingConflict = true }
 370        }
 371        .onChange(of: commands.showingConflict) { _, showing in
 372            guard showing else { return }
 373            commands.showingConflict = false
 374            if session.conflict != nil { panel = .conflict(UUID()) }
 375        }
 376        .onChange(of: workspace.changedFile?.version) { fileChangedOnDisk() }
 377    }
 378
 379    /// A column view edit at the heading starting at `start` in the open file.
 380    private func runInColumnView(_ command: any OrgCommand, _ start: Int, _ answers: [String: String]) -> CommandStep {
 381        guard let path = session.path else { return .failed("No file is open") }
 382        return session.perform(command, path: path, at: start, expect: nil, answers: answers)
 383    }
 384
 385    /// An open file takes in what changed on disk, and a clock started or stopped in Emacs
 386    /// becomes the one shown.
 387    private func fileChangedOnDisk() {
 388        guard let path = workspace.changedFile?.path else { return }
 389        session.fileChanged(path)
 390        if path.hasSuffix(".org") { syncClock(paths: [path]) }
 391    }
 392
 393    /// Open clocks in `paths`: at launch and as folders load, the agenda files.
 394    private func syncClock(paths: [String]) {
 395        guard !workspace.files.isEmpty, let message = clock.sync(session, paths: paths) else { return }
 396        commands.show(message)
 397    }
 398
 399    var body: some View {
 400        main
 401        .task(id: workspace.files.count) { syncClock(paths: workspace.agendaFilePaths()) }
 402        .onChange(of: ClockMenuState(running: clock.running, history: clock.history), initial: true) { _, state in
 403            if statusItem == nil { statusItem = ClockStatusItem { commands.run($0) } }
 404            statusItem?.update(state.running, recent: state.history.map(\.title))
 405        }
 406        .onChange(of: globalCapture, initial: true) { _, enabled in
 407            hotKey?.unregister()
 408            hotKey = enabled ? GlobalHotKey { perform("app.capture") } : nil
 409        }
 410        .onChange(of: commands.runRequest?.serial, initial: true) {
 411            if let id = commands.runRequest?.id { perform(id) }
 412        }
 413        .onChange(of: ConfigSync.shared.problems, initial: true) { _, problems in
 414            if let first = problems.first {
 415                commands.show(first + (problems.count > 1 ? " (and \(problems.count - 1) more)" : ""))
 416            }
 417        }
 418        .onChange(of: ConfigSync.shared.changedFile?.serial) {
 419            if ConfigSync.shared.changedFile?.name == "keymap.toml" { loadKeymap() }
 420        }
 421        .onChange(of: commands.jumpRequest?.id) {
 422            guard let request = commands.jumpRequest else { return }
 423            if request.path != session.path {
 424                session.open(request.path)
 425                selectedFile = request.path
 426            }
 427            session.reveal(request.offset)
 428        }
 429        .onChange(of: commands.focusSearch) { _, focus in
 430            if focus {
 431                searchFocused = true
 432                commands.focusSearch = false
 433            }
 434        }
 435        .fileImporter(isPresented: $commands.showingFolderPicker, allowedContentTypes: [.folder]) { result in
 436            guard case .success(let url) = result else { return }
 437            Task {
 438                do { try await workspace.addRoot(url) } catch { workspace.lastError = error.localizedDescription }
 439            }
 440        }
 441        .sheet(isPresented: $commands.showingQuickOpen) {
 442            QuickOpenView(workspace: workspace) { entry in
 443                commands.showingQuickOpen = false
 444                DispatchQueue.main.async {
 445                    restoreSheetTarget()
 446                    selectedFile = entry.path
 447                    if selectedFile == entry.path { session.open(entry.path) }
 448                }
 449            }
 450        }
 451        .alert("orgstar", isPresented: errorShown) {
 452            Button("OK") {
 453                workspace.lastError = nil
 454                session.lastError = nil
 455            }
 456        } message: {
 457            Text(workspace.lastError ?? session.lastError ?? "")
 458        }
 459        .task(id: ReminderKey(
 460            enabled: remindersEnabled, lead: reminderLead, subfolders: agendaSubfolders, files: workspace.files.count,
 461            changed: workspace.changedFile?.version, edits: session.editVersion, hour: hour
 462        )) {
 463            await updateReminders()
 464        }
 465        .task {
 466            while !Task.isCancelled {
 467                try? await Task.sleep(for: .seconds(3600))
 468                hour += 1
 469            }
 470        }
 471        // `org-resolve-clocks-if-idle`, checked every minute while a clock runs.
 472        .task(id: "\(clock.running?.start ?? "") \(clockIdleTime)") {
 473            guard clock.running != nil, clockIdleTime > 0 else { return }
 474            while !Task.isCancelled {
 475                try? await Task.sleep(for: .seconds(60))
 476                guard !Task.isCancelled, clock.running != nil, !clock.isResolving else { continue }
 477                let idle = ClockIdle.seconds()
 478                guard idle > Double(clockIdleTime * 60) else { continue }
 479                NSApp.requestUserAttention(.informationalRequest)
 480                report(await clock.resolveIdle(session, idleSince: Date().addingTimeInterval(-idle), ask: askClock))
 481            }
 482        }
 483        .task {
 484            DevelopmentHooks.scheduleSnapshot()
 485            pendingCarets = BufferRestore.restore(session)
 486            if let path = session.path, let caret = pendingCarets.removeValue(forKey: path) { session.reveal(caret) }
 487            // Files handed over at launch open after the restored buffers, and show.
 488            for path in AppDelegate.pendingOpens { session.open(path) }
 489            AppDelegate.pendingOpens = []
 490            for link in AppDelegate.pendingLinks + [DevelopmentHooks.urlToOpen].compactMap({ $0 }) { commands.handle(protocolURL: link) }
 491            AppDelegate.pendingLinks = []
 492            if let path = DevelopmentHooks.fileToOpen { selectedFile = path }
 493            if let root = DevelopmentHooks.rootToAdd { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
 494            if let commandList = DevelopmentHooks.commandToRun {
 495                // The file opened above needs its editor first.
 496                for _ in 0..<20 where DevelopmentHooks.fileToOpen != nil && commands.editor == nil { try? await Task.sleep(for: .milliseconds(100)) }
 497                for command in commandList.split(separator: ",") { perform(String(command)) }
 498                for answer in DevelopmentHooks.answers {
 499                    for _ in 0..<20 where commands.prompt == nil { try? await Task.sleep(for: .milliseconds(100)) }
 500                    commands.answer(answer)
 501                }
 502            }
 503            if let id = DevelopmentHooks.windowToOpen {
 504                if id == "settings" { openSettings() } else { openWindow(id: id) }
 505            }
 506            await workspace.refresh()
 507            workspace.startWatching()
 508        }
 509    }
 510
 511    /// The selection, or the whole file without one, on the clipboard as HTML, RTF and plain
 512    /// text, to paste formatted into mail and documents.
 513    private func copyRichText() {
 514        guard let path = session.path, let whole = session.document?.text, let editor = commands.editor else { return commands.show("No file is open") }
 515        let defaults = Preferences.orgSettings.resolvingSetupFiles(in: whole, path: path, read: OrgSettings.readFile)
 516        let selection = editor.context().selection.first { !$0.isEmpty }
 517        let selected = selection.map { (whole as NSString).substring(with: NSRange($0)) }
 518        let url = URL(fileURLWithPath: path)
 519        let html = HTMLExport.page(
 520            selected ?? whole, fallbackTitle: url.deletingPathExtension().lastPathComponent, settings: defaults, path: path, bodyOnly: selected != nil,
 521            codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme)
 522        )
 523        do {
 524            try RichTextExport.copy(html: html, directory: url.deletingLastPathComponent())
 525            commands.show(selected == nil ? "Copied the file as rich text" : "Copied the selection as rich text")
 526        } catch {
 527            commands.show("\(error)")
 528        }
 529    }
 530
 531    /// Whether the caret is in a heading's subtree, which the export dialog can export alone.
 532    private var exportSubtreeAvailable: Bool {
 533        guard let text = session.document?.text, let caret = commands.editor?.context().caret else { return false }
 534        return ExportScope.subtree(text, at: caret) != nil
 535    }
 536
 537    /// Where an export goes by default: `#+EXPORT_FILE_NAME`, or the subtree's
 538    /// `EXPORT_FILE_NAME`, else beside the file, with `ext`.
 539    private func exportTarget(_ ext: String, subtree: Bool) -> URL {
 540        let path = session.path ?? ""
 541        let text = session.document?.text ?? ""
 542        let caret = subtree ? commands.editor?.context().caret : nil
 543        return ExportScope.output(for: URL(fileURLWithPath: path), name: ExportScope.fileName(text, subtreeAt: caret), extension: ext)
 544    }
 545
 546    /// Writes the export where `#+EXPORT_FILE_NAME` says or beside the file, as Emacs's export
 547    /// dispatcher does, or to `destination`, and opens it with `open`. `subtree` exports the
 548    /// subtree at the caret alone; `bodyOnly` leaves out the title and page wrapper.
 549    private func export(_ format: String, to destination: URL? = nil, open: Bool = false, subtree: Bool = false, bodyOnly: Bool = false) {
 550        if format == "icalendar-agenda" || format == "icalendar-combined" { return exportAgendaCalendars(combined: format == "icalendar-combined") }
 551        guard let path = session.path, var text = session.document?.text else {
 552            commands.show("No file is open")
 553            return
 554        }
 555        let url = URL(fileURLWithPath: path)
 556        let base = url.deletingPathExtension()
 557        let defaults = Preferences.orgSettings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
 558        let open = open || format == "html-open"
 559        let caret = commands.editor?.context().caret ?? 0
 560        let whole = text
 561        if subtree {
 562            guard let narrowed = ExportScope.subtree(text, at: caret, settings: defaults) else { return commands.show("Not in a subtree") }
 563            text = narrowed
 564        }
 565        switch format {
 566        case "icalendar":
 567            do {
 568                let target = try ICalendarFiles.export(whole, path: path, settings: defaults, options: OrgPreferences.icalendarOptions(),
 569                                                       subtree: subtree ? caret : nil, destination: destination)
 570                commands.show("Exported to \(target.lastPathComponent)")
 571                if open { NSWorkspace.shared.open(target) }
 572            } catch {
 573                commands.show("Can't export: \(error.localizedDescription)")
 574            }
 575        case "html", "html-open", "markdown":
 576            let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
 577            let target = destination ?? ExportScope.output(for: url, name: name, extension: format == "markdown" ? "md" : "html")
 578            let content = format == "markdown"
 579                ? MarkdownExport.document(text, settings: defaults, path: path, bodyOnly: bodyOnly)
 580                : HTMLExport.page(
 581                    text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path, bodyOnly: bodyOnly,
 582                    codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme)
 583                )
 584            do {
 585                try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
 586                try content.write(to: target, atomically: true, encoding: .utf8)
 587                commands.show("Exported to \(target.lastPathComponent)")
 588                if open { NSWorkspace.shared.open(target) }
 589            } catch {
 590                commands.show("Can't write \(target.lastPathComponent): \(error.localizedDescription)")
 591            }
 592        case "print-pdf", "docx", "rtf", "plain-text":
 593            let ext = ["print-pdf": "pdf", "plain-text": "txt"][format] ?? format
 594            let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
 595            let target = destination ?? ExportScope.output(for: url, name: name, extension: ext)
 596            let html = HTMLExport.page(
 597                text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path,
 598                codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme)
 599            )
 600            let directory = url.deletingLastPathComponent()
 601            if format == "print-pdf" { commands.show("Exporting to PDF…") }
 602            Task {
 603                do {
 604                    let data: Data
 605                    switch format {
 606                    case "print-pdf": data = try await PDFExport.pdf(html: html, directory: directory)
 607                    case "docx": data = try RichTextExport.docx(RichTextExport.attributed(html: html, directory: directory))
 608                    case "rtf": data = try RichTextExport.rtf(RichTextExport.attributed(html: html, directory: directory))
 609                    default: data = Data(RichTextExport.plain(try RichTextExport.attributed(html: html, directory: directory)).utf8)
 610                    }
 611                    try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
 612                    try data.write(to: target, options: .atomic)
 613                    commands.show("Exported to \(target.lastPathComponent)")
 614                    if open { NSWorkspace.shared.open(target) }
 615                } catch {
 616                    commands.show("Can't export \(target.lastPathComponent): \(error)")
 617                }
 618            }
 619        default:
 620            let functions = ["pdf": "org-latex-export-to-pdf", "odt": "org-odt-export-to-odt", "latex": "org-latex-export-to-latex", "text": "org-ascii-export-to-ascii"]
 621            guard let function = functions[format] else { return }
 622            commands.show("Exporting with Emacs…")
 623            commands.runInEmacs {
 624                do {
 625                    // Emacs narrows to the subtree and reads EXPORT_FILE_NAME itself.
 626                    let point = subtree ? (whole as NSString).substring(to: min(caret, (whole as NSString).length)).unicodeScalars.count + 1 : nil
 627                    var written = URL(fileURLWithPath: try await EmacsRunner.export(
 628                        text: whole, path: path, function: function, subtree: point, bodyOnly: bodyOnly
 629                    ))
 630                    if let destination, destination.standardizedFileURL != written.standardizedFileURL {
 631                        try? FileManager.default.removeItem(at: destination)
 632                        try FileManager.default.moveItem(at: written, to: destination)
 633                        written = destination
 634                    }
 635                    commands.show("Exported to \(written.lastPathComponent)")
 636                    if open { NSWorkspace.shared.open(written) }
 637                } catch is CancellationError {
 638                    commands.show("Export canceled")
 639                } catch {
 640                    commands.show("\(error)")
 641                }
 642            }
 643        }
 644    }
 645
 646    /// `org-icalendar-export-agenda-files`, or with `combined`, `org-icalendar-combine-agenda-files`.
 647    private func exportAgendaCalendars(combined: Bool) {
 648        let paths = workspace.agendaFilePaths()
 649        let read = { (path: String) -> (text: String, settings: OrgSettings)? in
 650            guard let text = session.openDocuments.first(where: { $0.path == path })?.document.text ?? (try? String(contentsOfFile: path, encoding: .utf8)) else { return nil }
 651            return (text, Preferences.orgSettings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile))
 652        }
 653        do {
 654            let options = OrgPreferences.icalendarOptions()
 655            if combined {
 656                let url = try ICalendarFiles.combine(paths, to: OrgPreferences.icalendarCombinedFile(), options: options, read: read)
 657                commands.show("Exported \(paths.count) agenda files to \(url.lastPathComponent)")
 658            } else {
 659                let written = try ICalendarFiles.exportEach(paths, options: options, read: read)
 660                commands.show("Exported \(written.count) agenda files to iCalendar")
 661            }
 662        } catch {
 663            commands.show("Can't export: \(error.localizedDescription)")
 664        }
 665    }
 666
 667    /// `org-publish`, `org-publish-all`, `org-publish-current-file` and
 668    /// `org-publish-current-project`, with the projects in config.toml.
 669    private func publish(_ id: String) {
 670        let config = (try? String(contentsOf: UserConfig.file("config.toml"), encoding: .utf8)) ?? ""
 671        let loaded = Publish.projects(fromConfig: config, root: workspace.rootPaths.first)
 672        if let problem = loaded.problems.first { commands.show(problem) }
 673        guard !loaded.projects.isEmpty else { return commands.show("No [[publish]] projects in config.toml") }
 674        let read = { (path: String) -> String? in
 675            session.openDocuments.first { $0.path == path }?.document.text ?? (try? String(contentsOfFile: path, encoding: .utf8))
 676        }
 677        let codeStyle = HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme)
 678        func run(_ chosen: [PublishProject], only: String? = nil) {
 679            do {
 680                let report = try Publish.publish(chosen, all: loaded.projects, only: only, read: read) { function, text, path, bodyOnly in
 681                    let settings = Preferences.orgSettings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
 682                    if function == "org-md-publish-to-md" { return MarkdownExport.document(text, settings: settings, path: path, bodyOnly: bodyOnly) }
 683                    let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
 684                    return HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, bodyOnly: bodyOnly, codeStyle: codeStyle)
 685                }
 686                commands.show("Published \(report.published.count) files" + (report.skipped.isEmpty ? "" : ", \(report.skipped.count) up to date"))
 687            } catch {
 688                commands.show("\(error)")
 689            }
 690        }
 691        let current = session.path.map { Publish.projects(containing: $0, in: loaded.projects) } ?? []
 692        switch id {
 693        case "app.publish.all":
 694            run(loaded.projects)
 695        case "app.publish.current-file":
 696            guard let path = session.path, !current.isEmpty else { return commands.show("File is not part of any known project") }
 697            run([current[0]], only: path)
 698        case "app.publish.current-project":
 699            guard !current.isEmpty else { return commands.show("File is not part of any known project") }
 700            run([current[0]])
 701        default:
 702            let names = loaded.projects.map(\.name)
 703            commands.ask(Prompt(key: "project", message: "Publish project:", choices: names)) { answer in
 704                guard let answer, let project = loaded.projects.first(where: { $0.name == answer }) else { return }
 705                run([project])
 706            }
 707        }
 708    }
 709
 710    /// Work a command hands to the platform: tables recalculated in Emacs.
 711    private func runExternal(_ request: ExternalRequest) {
 712        switch request {
 713        case .openLink(let link):
 714            if let message = LinkOpener.open(link, session: session, workspace: workspace) { commands.show(message) }
 715            // `org-occur` for a regexp link, once the editor shows the file.
 716            if let regexp = Links.regexpSearch(link) {
 717                DispatchQueue.main.async { commands.editor?.perform(SparseTreeCommand(), answers: ["sparse": "/", "regexp": regexp]) }
 718            }
 719        case .tangle(let scope):
 720            commands.show(session.tangle(scope))
 721        case .agenda(let start, let days):
 722            commands.agendaRequest = (start, days)
 723            openWindow(id: "agenda")
 724        case .editBlock(let edit):
 725            blockEdit = BlockEditRequest(edit: edit)
 726        case .columnView(let view):
 727            panel = .columns(UUID(), view)
 728        case .emacsTable(let table, let point, let form, let reason, let lisp):
 729            let run = {
 730                commands.show("Recalculating in Emacs (\(reason))…")
 731                commands.runInEmacs { commands.show(await session.recalculateInEmacs(table: table, point: point, form: form)) }
 732            }
 733            guard lisp, let path = session.path, let text = session.document?.text else { return run() }
 734            let content = (text as NSString).substring(with: NSRange(location: table.lowerBound, length: min((text as NSString).length, table.upperBound + 2000) - table.lowerBound))
 735            if trust.isTrusted(path: path, content: content) { return run() }
 736            commands.ask(Prompt(key: "confirm", message: "This table's formulas run Lisp. Run them? (yes, no, always)", choices: ["yes", "no", "always"])) { answer in
 737                switch answer {
 738                case "always":
 739                    trust.trust(path: path, content: content)
 740                    run()
 741                case "yes": run()
 742                default: commands.show("Not recalculated")
 743                }
 744            }
 745        case .babel(let job):
 746            let run = {
 747                commands.show("Running \(job.language) block… (⌘. to cancel)")
 748                session.startBabel(job) { commands.show($0) }
 749            }
 750            guard let path = session.path else { return }
 751            if !job.alwaysAsk, trust.isTrusted(path: path, content: job.blockText) { return run() }
 752            let choices = job.alwaysAsk ? ["yes", "no"] : ["yes", "no", "always"]
 753            commands.ask(Prompt(key: "confirm", message: "Run this \(job.language) block? (\(choices.joined(separator: ", ")))", choices: choices)) { answer in
 754                switch answer {
 755                case "always":
 756                    trust.trust(path: path, content: job.blockText)
 757                    run()
 758                case "yes": run()
 759                default: commands.show("Not run")
 760                }
 761            }
 762        }
 763    }
 764
 765    private struct ReminderKey: Hashable {
 766        var enabled: Bool
 767        var lead: Int
 768        var subfolders: Bool
 769        var files: Int
 770        var changed: Int?
 771        var edits: Int
 772        var hour: Int
 773    }
 774
 775    /// Sets the notifications for the next week's timed entries, once edits pause.
 776    private func updateReminders() async {
 777        guard let scheduler else { return }
 778        guard remindersEnabled else {
 779            await scheduler.clear()
 780            return
 781        }
 782        try? await Task.sleep(for: .seconds(2))
 783        guard !Task.isCancelled, !workspace.files.isEmpty else { return }
 784        let agenda = reminderAgenda ?? AgendaModel(workspace: workspace)
 785        reminderAgenda = agenda
 786        agenda.includeSubfolders = agendaSubfolders
 787        let open = session.openTexts
 788        let reminders = await agenda.reminders(open: open, lead: reminderLead)
 789        guard !Task.isCancelled else { return }
 790        await scheduler.reconcile(reminders)
 791    }
 792
 793    private func loadKeymap() {
 794        let loaded = KeymapLoader.load(preset, commands: Set(EditorCommands.all.map(\.id)))
 795        keymap = loaded.keymap
 796        commands.keymap = loaded.keymap
 797        commands.modal = preset.isModal
 798        if let first = loaded.problems.first {
 799            let more = loaded.problems.count > 1 ? " (and \(loaded.problems.count - 1) more)" : ""
 800            commands.show("keymap.toml: \(first)\(more)")
 801        }
 802    }
 803
 804    /// `SPC b b`: open buffers, most recent first, by name (with the folder when names repeat).
 805    private func switchBuffer() {
 806        let paths = session.recentPaths.dropFirst() + session.recentPaths.prefix(1)
 807        let labels = paths.map(session.bufferName)
 808        guard !labels.isEmpty else { return commands.show("No buffers are open") }
 809        commands.ask(Prompt(key: "buffer", message: "Switch to buffer:", choices: labels)) { answer in
 810            guard let answer, let index = labels.firstIndex(of: answer) else { return }
 811            session.open(Array(paths)[index])
 812        }
 813    }
 814
 815    /// Runs a command from a key, the palette or the Org menu.
 816    private func perform(_ id: String) {
 817        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.")
 818        if orgOnly, !session.isOrg {
 819            commands.show("Not an org file")
 820            return
 821        }
 822        switch id {
 823        case "app.save":
 824            if !session.save(), session.conflict != nil { commands.showingConflict = true }
 825        case "app.quit": NSApp.terminate(nil)
 826        case "app.save-all":
 827            if !session.saveAll(), session.conflict != nil { commands.showingConflict = true }
 828        case "app.buffer.switch": switchBuffer()
 829        case "app.buffer.next": session.cycle(1)
 830        case "app.buffer.previous": session.cycle(-1)
 831        case "app.buffer.last": session.showPrevious()
 832        case "app.buffer.kill":
 833            guard let path = session.path else {
 834                NSApp.keyWindow?.performClose(nil)
 835                return
 836            }
 837            if UnsavedChanges.resolve(session) { session.kill(path) }
 838        case "app.buffer.kill-others":
 839            let others = session.openPaths.filter { $0 != session.path }
 840            if UnsavedChanges.resolve(session, paths: others) { others.forEach(session.kill) }
 841        case "app.buffer.kill-all":
 842            let all = session.openPaths
 843            if UnsavedChanges.resolve(session, paths: all) { all.forEach(session.kill) }
 844        case "app.toggle-tab-bar": showTabBar.toggle()
 845        case "app.split-below": paneWindow?.split(.vertical)
 846        case "app.split-right": paneWindow?.split(.horizontal)
 847        case "app.pane-close":
 848            guard let window = paneWindow, window.paneCount > 1 else { return commands.show("Attempt to delete the only pane") }
 849            commands.store.releasePane(window.focused)
 850            window.close(window.focused)
 851            focusPane(window)
 852        case "app.pane-only":
 853            guard let window = paneWindow else { return }
 854            for id in window.layout.panes where id != window.focused { commands.store.releasePane(id) }
 855            window.closeOthers()
 856            focusPane(window)
 857        case "app.pane-next":
 858            guard let window = paneWindow else { return }
 859            window.focusNext()
 860            focusPane(window)
 861        case "app.window-new": openWindow(id: "editor")
 862        case "app.babel.cancel":
 863            if session.isRunningBabel {
 864                session.cancelBabel()
 865            } else if let task = commands.emacsTask {
 866                task.cancel()
 867            } else {
 868                commands.show("Nothing is running")
 869            }
 870        case "app.toggle-outline": toggleOutline()
 871        case "app.toggle-backlinks": backlinksShown.toggle()
 872        case "app.toggle-inspector": inspectorShown.toggle()
 873        case "app.toggle-markup": showMarkup.toggle()
 874        case "app.toggle-line-numbers": showLineNumbers.toggle()
 875        case "app.import-emacs": showingImport = true
 876        case "app.edit-config": commands.jump(path: UserConfig.configFile.path, offset: 0)
 877        case "app.quick-open": commands.showingQuickOpen = true
 878        case "app.palette": commands.showingPalette = true
 879        case "app.search": commands.focusSearch = true
 880        case "app.reload-keymap":
 881            loadKeymap()
 882            commands.show("Keymap reloaded")
 883        case "app.refile", "app.refile.copy":
 884            let keep = id == "app.refile.copy"
 885            let targets = workspace.refileTargets(openPath: session.path, document: session.document)
 886            commands.ask(Prompt(key: "refile", message: keep ? "Copy to:" : "Refile to:", choices: targets.map(\.label))) { answer in
 887                guard let answer else { return }
 888                if let target = targets.first(where: { $0.label == answer }) {
 889                    if let message = session.refile(to: target, keep: keep) { commands.show(message) }
 890                    return
 891                }
 892                // `org-refile-allow-creating-parent-nodes`: `parent/new` adds the heading first.
 893                let creating = OrgPreferences.refileSettings().creating
 894                guard creating != .no, let (parent, child) = RefileSettings.newNode(answer, in: targets) else { return commands.show("Invalid target location") }
 895                let create = {
 896                    switch session.createRefileChild(under: parent, title: child) {
 897                    case .success(let target): if let message = session.refile(to: target, keep: keep) { commands.show(message) }
 898                    case .failure(.message(let message)): commands.show(message)
 899                    }
 900                }
 901                guard creating == .confirm else { return create() }
 902                commands.ask(Prompt(key: "confirm", message: "Create new node \"\(child)\"?", choices: ["yes", "no"])) { reply in
 903                    if reply == "yes" { create() }
 904                }
 905            }
 906        case "app.refile.goto":
 907            // `C-u C-c C-w`: the target heading, or the end of a file.
 908            let targets = workspace.refileTargets(openPath: session.path, document: session.document)
 909            commands.ask(Prompt(key: "refile", message: "Goto:", choices: targets.map(\.label))) { answer in
 910                guard let answer, let target = targets.first(where: { $0.label == answer }) else { return }
 911                commands.jump(path: target.path, offset: target.start ?? Int.max)
 912            }
 913        case "app.archive":
 914            if let message = session.archive() { commands.show(message) }
 915        case "app.table-import":
 916            // `org-table-import`: a TSV, CSV or space-separated file becomes a table at point.
 917            guard let editor = commands.editor else { return commands.show("No file is open") }
 918            let panel = NSOpenPanel()
 919            panel.allowedContentTypes = [.commaSeparatedText, .tabSeparatedText, .plainText]
 920            guard panel.runModal() == .OK, let url = panel.url else { return }
 921            guard let contents = try? String(contentsOf: url, encoding: .utf8) else { return commands.show("Can't read \(url.lastPathComponent)") }
 922            editor.perform(ImportTable(contents: contents))
 923        case "app.table-export":
 924            // `org-table-export`: CSV for a .csv name, else TSV.
 925            guard let editor = commands.editor else { return commands.show("No file is open") }
 926            let context = editor.context()
 927            guard ImportTable.exportText(context.text, at: context.caret, path: "") != nil else { return commands.show("No table at point") }
 928            let panel = NSSavePanel()
 929            panel.nameFieldStringValue = "table.csv"
 930            guard panel.runModal() == .OK, let url = panel.url,
 931                  let text = ImportTable.exportText(context.text, at: context.caret, path: url.path) else { return }
 932            do {
 933                try text.write(to: url, atomically: true, encoding: .utf8)
 934                commands.show("Export done.")
 935            } catch {
 936                commands.show("File not written: \(error.localizedDescription)")
 937            }
 938        case "org.subtree.paste":
 939            guard let text = NSPasteboard.general.string(forType: .string) else { return commands.show("The clipboard is empty") }
 940            commands.editor?.perform(PasteSubtree(text: text))
 941        case "org.link.insert":
 942            commands.editor?.perform(InsertLink(stored: commands.storedLinks, file: session.path))
 943        case "org.link.store":
 944            guard let editor = commands.editor, let path = session.path else { return commands.show("No method for storing a link from this buffer") }
 945            commands.storeLink(Links.store(in: editor.context(), path: Links.abbreviate(path, home: NSHomeDirectory())))
 946        case "org.id.store-link":
 947            guard let editor = commands.editor, let path = session.path else { return }
 948            if case .commit = editor.perform(CreateID()),
 949               let link = Links.storeID(in: editor.context(), fileName: (path as NSString).lastPathComponent) {
 950                commands.storeLink(link)
 951            }
 952        case "app.agenda":
 953            openWindow(id: "agenda")
 954        case "app.clock.in":
 955            clockIn(.caret)
 956        case "app.clock.in-recent":
 957            clockIn(.select)
 958        case "app.clock.in-last":
 959            clockIn(.last)
 960        case let id where id.hasPrefix("app.clock.history."):
 961            if let index = Int(id.dropFirst("app.clock.history.".count)), index < clock.history.count { clockIn(.task(clock.history[index])) }
 962        case "app.clock.out":
 963            commands.show(clock.clockOut(session))
 964        case "app.clock.cancel":
 965            commands.show(clock.clockOut(session, cancel: true))
 966        case "app.clock.goto":
 967            let found = clock.goto(session)
 968            if let location = found.location { commands.jump(path: location.path, offset: location.offset) }
 969            if let message = found.message { commands.show(message) }
 970        case "app.clock.goto-recent":
 971            Task {
 972                let found = await clock.gotoRecent(session, ask: askClock)
 973                if let location = found.location { commands.jump(path: location.path, offset: location.offset) }
 974                if let message = found.message { commands.show(message) }
 975            }
 976        case "app.clock.default":
 977            commands.show(clock.markDefault(session))
 978        case "app.clock.resolve":
 979            Task { report(await clock.resolveOpenClocks(session, paths: orgFiles, ask: askClock)) }
 980        case "app.clock.report":
 981            openWindow(id: "clock-report")
 982        case "app.board":
 983            openWindow(id: "board")
 984        case "app.capture":
 985            NSApp.activate()
 986            openWindow(id: "capture")
 987        case "app.revert":
 988            // `:e`: the file as it is on disk; unsaved changes go to recovery.
 989            guard session.path != nil else { return commands.show("No file is open") }
 990            session.useDiskVersion()
 991            commands.show("Reverted to the file on disk")
 992        case "app.sync-conflicts":
 993            guard session.path != nil else { return commands.show("No file is open") }
 994            panel = .syncCopies(UUID())
 995        case "app.recovery":
 996            guard session.path != nil else { return commands.show("No file is open") }
 997            panel = .recovery(UUID())
 998        case "app.copy-rich-text":
 999            copyRichText()
1000        case "app.export-dialog":
1001            guard let path = session.path else { return commands.show("No file is open") }
1002            panel = .export(UUID(), URL(fileURLWithPath: path))
1003        case let id where id.hasPrefix("app.export."):
1004            export(String(id.dropFirst("app.export.".count)))
1005        case let id where id.hasPrefix("app.publish"):
1006            publish(id)
1007        default:
1008            if let editor = commands.editor { editor.run(id) } else { commands.show("No file is open") }
1009        }
1010    }
1011
1012    private var askClock: ClockModel.Ask { commands.askClock }
1013
1014    /// The files `org-resolve-clocks` looks through: the workspace's org files.
1015    private var orgFiles: [String] { workspace.files.filter { $0.kind == .org }.map(\.path) }
1016
1017    private func clockIn(_ target: ClockModel.Target) {
1018        Task { report(await clock.clockIn(session, target: target, paths: orgFiles, ask: askClock)) }
1019    }
1020
1021    /// The last message of a clock command, and the clock to show for `j`.
1022    private func report(_ outcome: ClockModel.Outcome) {
1023        if let jump = outcome.jump { commands.jump(path: jump.path, offset: jump.offset) }
1024        if let message = outcome.messages.last(where: { !$0.isEmpty }) { commands.show(message) }
1025    }
1026
1027    private var errorShown: Binding<Bool> {
1028        Binding(get: { workspace.lastError != nil || session.lastError != nil }, set: { _ in })
1029    }
1030}
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