Sources/Orgstar/ContentView.swift

72f19c1f379646b2cfc45c5053a72e5997fbef36
orgstar/Sources/Orgstar/ContentView.swift

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