Sources/Orgstar/ContentView.swift

71cfd8421de8b3d3c1fbdc9f394e56b267ec23e1
orgstar/Sources/Orgstar/ContentView.swift

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