Sources/Orgstar/ContentView.swift

de2aded7684eed392547e008fce57921e637d7bf
orgstar/Sources/Orgstar/ContentView.swift

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