Sources/Orgstar/ContentView.swift

29b770d6b2f9edcc6607ab4a46db6c659dd12c1d
orgstar/Sources/Orgstar/ContentView.swift

1603 lines · 91789 bytes

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