Sources/Orgstar/ContentView.swift

1ea33dc0867950dbc28a6b45f3ead9b1ff48b086
orgstar/Sources/Orgstar/ContentView.swift

1673 lines · 95855 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"
 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 "latex" where exportNative("LaTeX", extension: "tex", whole: whole, url: url, to: destination, open: open, subtree: subtree ? caret : nil, bodyOnly: bodyOnly, settings: defaults, export: {
 748            try LaTeXExport.document(text, settings: defaults, path: path, bodyOnly: bodyOnly, author: NSFullUserName(), language: OrgPreferences.exportLanguage(), file: true)
 749        }):
 750            break
 751        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: {
 752            try ASCIIExport.document(text, settings: defaults, path: path, bodyOnly: bodyOnly, author: NSFullUserName(), language: OrgPreferences.exportLanguage(), file: true)
 753        }):
 754            break
 755        case "odt":
 756            let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
 757            guard let target = destination ?? writable(ExportScope.output(for: url, name: name, extension: "odt")) else { return }
 758            // A missing image stops the export, so offer access to them first.
 759            _ = reach(ODTExport.imageFiles(text, settings: defaults, path: path).filter(WorkspaceModel.isThere))
 760            do {
 761                let data = try ODTExport.document(text, settings: defaults, path: path, author: NSFullUserName(), language: OrgPreferences.exportLanguage())
 762                try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
 763                try data.write(to: target, options: .atomic)
 764                commands.show(ExportSettings.exported(target.lastPathComponent, subtree: subtree, bodyOnly: bodyOnly))
 765                if open { NSWorkspace.shared.open(target) }
 766            } catch {
 767                commands.show(String(localized: "Can't export \(target.lastPathComponent): \(error.localizedDescription)"))
 768            }
 769        case "print-pdf", "docx", "rtf", "plain-text":
 770            let ext = ["print-pdf": "pdf", "plain-text": "txt"][format] ?? format
 771            let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
 772            guard let target = destination ?? writable(ExportScope.output(for: url, name: name, extension: ext)) else { return }
 773            let html = HTMLExport.page(
 774                text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path,
 775                codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme), language: OrgPreferences.exportLanguage()
 776            )
 777            let directory = url.deletingLastPathComponent()
 778            // Images that can't be read are left out, so offer access to them first.
 779            _ = reach(PDFExport.imageFiles(html, directory: directory).filter(WorkspaceModel.isThere))
 780            if format == "print-pdf" { commands.show(String(localized: "Exporting to PDF…")) }
 781            Task {
 782                do {
 783                    let data: Data
 784                    switch format {
 785                    case "print-pdf": data = try await PDFExport.pdf(html: html, directory: directory, options: OrgPreferences.pdfOptions())
 786                    case "docx": data = try RichTextExport.docx(html: html, directory: directory)
 787                    case "rtf": data = try RichTextExport.rtf(RichTextExport.attributed(html: html, directory: directory))
 788                    default: data = Data(RichTextExport.plain(try RichTextExport.attributed(html: html, directory: directory)).utf8)
 789                    }
 790                    try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
 791                    try data.write(to: target, options: .atomic)
 792                    commands.show(ExportSettings.exported(target.lastPathComponent, subtree: subtree, bodyOnly: bodyOnly))
 793                    if open { NSWorkspace.shared.open(target) }
 794                } catch {
 795                    commands.show(String(localized: "Can't export \(target.lastPathComponent): \(String(describing: error))"))
 796                }
 797            }
 798        default:
 799            #if !APPSTORE
 800            let functions = ["pdf": "org-latex-export-to-pdf", "latex": "org-latex-export-to-latex", "text": "org-ascii-export-to-ascii"]
 801            guard let function = functions[format] else { return }
 802            if let refusal = session.refusesEmacsCopy(path) { return commands.show(refusal) }
 803            commands.show(String(localized: "Exporting with Emacs…"))
 804            commands.runInEmacs {
 805                do {
 806                    // Emacs narrows to the subtree and reads EXPORT_FILE_NAME itself.
 807                    let point = subtree ? (whole as NSString).substring(to: min(caret, (whole as NSString).length)).unicodeScalars.count + 1 : nil
 808                    var written = URL(fileURLWithPath: try await EmacsRunner.export(
 809                        text: whole, path: path, function: function, subtree: point, bodyOnly: bodyOnly
 810                    ))
 811                    if let destination, destination.standardizedFileURL != written.standardizedFileURL {
 812                        try? FileManager.default.removeItem(at: destination)
 813                        try FileManager.default.moveItem(at: written, to: destination)
 814                        written = destination
 815                    }
 816                    commands.show(ExportSettings.exported(written.lastPathComponent, subtree: subtree, bodyOnly: bodyOnly))
 817                    if open { NSWorkspace.shared.open(written) }
 818                } catch is CancellationError {
 819                    commands.show(String(localized: "Export canceled"))
 820                } catch {
 821                    commands.show("\(error)")
 822                }
 823            }
 824            #else
 825            let title = EditorCommands.all.first { $0.id == "app.export." + format }?.title
 826            commands.show(Self.unavailable(title ?? format))
 827            #endif
 828        }
 829    }
 830
 831    /// Writes what `export` makes, as ox does for `format`. False when the native export can't
 832    /// match Emacs and Emacs is installed to export instead; otherwise the reason is shown.
 833    private func exportNative(
 834        _ format: String, extension ext: String, whole: String, url: URL, to destination: URL?, open: Bool, subtree: Int?, bodyOnly: Bool, settings: OrgSettings,
 835        export: () throws -> String
 836    ) -> Bool {
 837        let content: String
 838        do {
 839            content = try export()
 840        } catch {
 841            #if !APPSTORE
 842            if EmacsRunner.executable() != nil { return false }
 843            #endif
 844            commands.show(String(localized: "Can't export to \(format): \(error.localizedDescription)"))
 845            return true
 846        }
 847        let name = ExportScope.fileName(whole, subtreeAt: subtree, settings: settings)
 848        guard let target = destination ?? writable(ExportScope.output(for: url, name: name, extension: ext)) else { return true }
 849        do {
 850            try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
 851            try content.write(to: target, atomically: true, encoding: .utf8)
 852            commands.show(ExportSettings.exported(target.lastPathComponent, subtree: subtree != nil, bodyOnly: bodyOnly))
 853            if open { NSWorkspace.shared.open(target) }
 854        } catch {
 855            commands.show(String(localized: "Can't write \(target.lastPathComponent): \(error.localizedDescription)"))
 856        }
 857        return true
 858    }
 859
 860    /// `url`; in the App Store build, when the sandbox keeps orgstar out of its folder, `url` once
 861    /// that folder is granted, or where a save panel puts it instead. Nil when canceled.
 862    private func writable(_ url: URL) -> URL? {
 863        #if APPSTORE
 864        guard let folder = workspace.foldersToGrant(for: [url.path]).first else { return url }
 865        let elsewhere = String(localized: "Save Elsewhere…", comment: "Button that asks where an export goes instead")
 866        switch GrantAccess.ask(folder, workspace: workspace, alternative: elsewhere) {
 867        case .granted: return url
 868        case .canceled: return nil
 869        case .alternative: break
 870        }
 871        let panel = NSSavePanel()
 872        panel.directoryURL = url.deletingLastPathComponent()
 873        panel.nameFieldStringValue = url.lastPathComponent
 874        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")
 875        return panel.runModal() == .OK ? panel.url : nil
 876        #else
 877        return url
 878        #endif
 879    }
 880
 881    private func saveBuffers() {
 882        #if APPSTORE
 883        BufferRestore.save(session, workspace: workspace)
 884        #else
 885        BufferRestore.save(session)
 886        #endif
 887    }
 888
 889    /// In the App Store build, asks for the folders outside the sidebar's folders that `paths`
 890    /// need. False when one is still out of reach.
 891    private func reach(_ paths: @autoclosure () -> [String], directories: Bool = false) -> Bool {
 892        #if APPSTORE
 893        GrantAccess.reach(paths(), directories: directories, workspace: workspace)
 894        #else
 895        true
 896        #endif
 897    }
 898
 899    /// In the App Store build, offers access to the setup files and includes of `text` that
 900    /// can't be read. False, with a message, when an include still can't be read, rather than
 901    /// exporting it as an empty line.
 902    private func readsIncludes(_ text: String, path: String) -> Bool {
 903        #if APPSTORE
 904        let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
 905        var setupFiles: [String] = []
 906        _ = Preferences.orgSettings.resolvingSetupFiles(in: text, path: path) { file in
 907            let contents = OrgSettings.readFile(file)
 908            if contents == nil, WorkspaceModel.isThere(file) { setupFiles.append(file) }
 909            return contents
 910        }
 911        let includes = ExportPreprocess.unreadableIncludes(text, directory: directory).filter(WorkspaceModel.isThere)
 912        guard !(setupFiles + includes).isEmpty else { return true }
 913        _ = reach(setupFiles + includes)
 914        guard let unreadable = ExportPreprocess.unreadableIncludes(text, directory: directory).first else { return true }
 915        commands.show(String(localized: "Can't include \(OrgPaths.abbreviatingWithTilde(unreadable)).", comment: "Export stopped by an #+INCLUDE file that can't be read"))
 916        return false
 917        #else
 918        return true
 919        #endif
 920    }
 921
 922    /// Says a command doesn't run in this build.
 923    static func unavailable(_ title: String) -> String {
 924        String(localized: "\(CommandTitle.localized(title)) isn't available.", comment: "A command the Mac App Store build leaves out")
 925    }
 926
 927    /// `org-icalendar-export-agenda-files`, or with `combined`, `org-icalendar-combine-agenda-files`.
 928    private func exportAgendaCalendars(combined: Bool) {
 929        let paths = workspace.agendaFilePaths()
 930        guard reach(paths + (combined ? [OrgPreferences.icalendarCombinedFile()] : [])) else { return }
 931        let read = { (path: String) -> (text: String, settings: OrgSettings)? in
 932            guard let text = session.exportText(of: path) else { return nil }
 933            return (text, Preferences.orgSettings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile))
 934        }
 935        let note = paths.contains(where: session.exportLeavesOut) ? " " + DocumentSession.exportNote : ""
 936        do {
 937            let options = OrgPreferences.icalendarOptions()
 938            if combined {
 939                let url = try ICalendarFiles.combine(paths, to: OrgPreferences.icalendarCombinedFile(), options: options, read: read)
 940                commands.show(String(localized: "Exported \(paths.count) agenda files to \(url.lastPathComponent)") + note)
 941            } else {
 942                let written = try ICalendarFiles.exportEach(paths, options: options, read: read)
 943                commands.show(String(localized: "Exported \(written.count) agenda files to iCalendar") + note)
 944            }
 945        } catch {
 946            commands.show(String(localized: "Can't export: \(error.localizedDescription)"))
 947        }
 948    }
 949
 950    /// org-crypt's commands at the caret, through the passphrase sheet.
 951    private func crypt(_ id: String) {
 952        if id == "app.crypt.save" {
 953            guard let path = session.path, let hold = session.held[path] else { return }
 954            panel = .crypt(UUID(), CryptRequest.save(path, hold: hold))
 955            return
 956        }
 957        guard let editor = commands.editor, let path = session.path else { return commands.show(String(localized: "No file is open")) }
 958        let caret = editor.context().caret
 959        let text = editor.context().text
 960        switch id {
 961        case "app.crypt.forget-passphrase":
 962            session.forgetPassphrase(for: path)
 963            commands.show(String(localized: "Passphrase forgotten for \((path as NSString).lastPathComponent)"))
 964        case "app.crypt.encrypt-entries":
 965            panel = .crypt(UUID(), CryptRequest(mode: .encryptAll(tag: OrgPreferences.cryptTag()), path: path, offset: caret))
 966        default:
 967            guard OrgCrypt.heading(text, at: caret) != nil else { return commands.show(String(localized: "Before first headline")) }
 968            if id == "app.crypt.encrypt-entry" {
 969                guard OrgCrypt.encryptedRange(text, at: caret) == nil else { return commands.show(String(localized: "The entry is encrypted already")) }
 970                panel = .crypt(UUID(), CryptRequest(mode: .encrypt, path: path, offset: caret))
 971            } else {
 972                guard OrgCrypt.encryptedRange(text, at: caret) != nil else { return commands.show(String(localized: "Not an encrypted entry")) }
 973                panel = .crypt(UUID(), CryptRequest(mode: id == "app.crypt.open-entry" ? .open : .decryptInPlace, path: path, offset: caret))
 974            }
 975        }
 976    }
 977
 978    /// org-roam's daily notes and nodes.
 979    private var roamActions: RoamActions {
 980        var actions = RoamActions(
 981            session: session, roots: { [workspace] in workspace.rootPaths },
 982            nodes: { [workspace, session] in try workspace.nodes(overlay: workspace.overlay(session.openDocuments)) },
 983            show: { [commands] in commands.show($0) }, ask: { [commands] in commands.ask($0, reply: $1) },
 984            open: { [commands] path, offset in commands.jump(path: path, offset: offset) },
 985            insertLink: { [commands] link, title in
 986                guard let editor = commands.editor else { return commands.show(String(localized: "No file is open")) }
 987                let context = editor.context()
 988                let range = context.selection.first ?? context.caret..<context.caret
 989                let selected = (context.text as NSString).substring(with: NSRange(range))
 990                let text = Denote.linkText(link, description: selected.isEmpty ? title : selected, inFile: context.options.filePath)
 991                let end = range.lowerBound + (text as NSString).length
 992                editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: [TextEdit(range: range, replacement: text)], selection: [end..<end])))
 993            },
 994            refresh: { [workspace] in Task { await workspace.refresh() } })
 995        actions.capture = { [commands] in commands.capture(roam: $0) }
 996        #if APPSTORE
 997        actions.reachFolders = { [workspace] in GrantAccess.reach($0, directories: true, workspace: workspace) }
 998        #endif
 999        return actions
1000    }
1001
1002    /// Insert Citation… and following citations.
1003    private var citationActions: CitationActions {
1004        var actions = CitationActions(
1005            session: session, context: { [commands] in commands.editor?.context() },
1006            perform: { [commands] in _ = commands.editor?.perform($0) },
1007            show: { [commands] in commands.show($0) }, ask: { [commands] in commands.ask($0, reply: $1) },
1008            present: { citationEntry = $0 })
1009        #if APPSTORE
1010        actions.reach = { [workspace] in GrantAccess.reach($0, workspace: workspace) }
1011        #endif
1012        return actions
1013    }
1014
1015    /// org-attach's commands for the entry at the caret.
1016    private var attachActions: AttachActions {
1017        AttachActions(
1018            entry: { [commands, session] in
1019                guard let editor = commands.editor, let path = session.path else { return nil }
1020                let context = editor.context()
1021                return Attachments.Entry(text: context.text, offset: context.caret, path: path, options: context.options)
1022            },
1023            apply: { applyText($0, caret: $1) }, show: { [commands] in commands.show($0) }, ask: { [commands] in commands.ask($0, reply: $1) },
1024            storeLink: { [commands] in _ = StoredLink.add($0, to: &commands.storedLinks) },
1025            open: { [session, workspace, commands] file in
1026                if let message = LinkOpener.open(OrgLink(type: "file", path: file, raw: "file:" + file), session: session, workspace: workspace, ask: commands.ask) { commands.show(message) }
1027            },
1028            reveal: { NSWorkspace.shared.open(URL(fileURLWithPath: $0, isDirectory: true)) },
1029            pick: { method in
1030                let panel = NSOpenPanel()
1031                panel.canChooseDirectories = true
1032                panel.allowsMultipleSelection = true
1033                panel.message = "File to keep as an attachment"
1034                guard panel.runModal() == .OK else { return }
1035                #if APPSTORE
1036                // The sandbox can remove only files in the sidebar's folders, and links nothing.
1037                if method == .mv, let outside = panel.urls.first(where: { !workspace.contains($0) }) {
1038                    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"))
1039                }
1040                guard method == .cp || method == .mv else { return }
1041                #endif
1042                self.attachActions.attach(panel.urls, method: method)
1043            })
1044    }
1045
1046    /// The sheet a panel shows.
1047    @ViewBuilder
1048    private func panelView(_ panel: Panel) -> some View {
1049        switch panel {
1050        case .columns(_, let view):
1051            ColumnViewSheet(view: view, run: runInColumnView, document: { session.document.map { ($0.text, $0.tree) } }) { offset in
1052                commands.editor?.reveal(offset)
1053            }
1054        case .export(_, let source):
1055            ExportSheet(source: source, inSubtree: exportSubtreeAvailable, target: exportTarget) { format, destination, open, subtree, bodyOnly in
1056                export(format, to: destination, open: open, subtree: subtree, bodyOnly: bodyOnly)
1057            }
1058        case .plot(_, let plot):
1059            PlotSheet(content: .chart(plot))
1060        case .plotImage(_, let url):
1061            PlotSheet(content: .image(url))
1062        case .shareSubtree(_, let share):
1063            ShareSubtreeSheet(share: share) { commands.show($0) }
1064        case .crypt(_, let request):
1065            CryptSheet(request: request, session: session, text: { session.document(of: request.path)?.text ?? "" }, apply: { applyText($0) }) { message in
1066                self.panel = nil
1067                // An encrypted file left closed: the sidebar shows the open file again.
1068                if case .openFile = request.mode, !session.isOpen(request.path) { selectedFile = session.path }
1069                if let message { commands.show(message) }
1070            }
1071        case .conflict:
1072            ConflictSheet(session: session)
1073        case .syncCopies:
1074            SyncConflictSheet(session: session) { commands.show($0) }
1075        case .recovery:
1076            HistorySheet(session: session) { commands.show($0) }
1077        }
1078    }
1079
1080    /// What Replace in Files starts with (the selection on one line) or a rename (the tag or
1081    /// keyword at the caret).
1082    private func replaceInitial(for kind: ReplaceKind) -> String {
1083        guard let editor = commands.editor else { return "" }
1084        let context = editor.context()
1085        if kind == .replace {
1086            let selected = context.selection.first.map { (context.text as NSString).substring(with: NSRange($0)) } ?? ""
1087            return selected.contains("\n") ? "" : selected
1088        }
1089        return kind.initial(text: context.text, caret: context.caret, keywords: context.tree.settings.todoKeywordNames)
1090    }
1091
1092    /// `new` in place of the buffer's text, as one edit, with the caret at `caret` or where it was.
1093    private func applyText(_ new: String, caret: Int? = nil) {
1094        guard let editor = commands.editor else { return }
1095        let context = editor.context()
1096        let caret = min(caret ?? context.caret, (new as NSString).length)
1097        editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
1098    }
1099
1100    /// `org-plot/gnuplot` for the table at the caret: through gnuplot when it's installed, as
1101    /// Emacs runs it, else drawn here; written to `file:` when the options name one, else shown.
1102    private func plotTable() {
1103        guard let editor = commands.editor, let path = session.path else { return commands.show(String(localized: "No file is open")) }
1104        let context = editor.context()
1105        let plot: TablePlot.Plot
1106        do { plot = try TablePlot.plot(context.text, at: context.caret) } catch { return commands.show("\(error)") }
1107        let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
1108        #if !APPSTORE
1109        if let gnuplot = PlotOutput.gnuplot {
1110            commands.show(String(localized: "Plotting with gnuplot…"))
1111            Task {
1112                do {
1113                    let image = try await PlotOutput.runGnuplot(plot, directory: directory, gnuplot: gnuplot)
1114                    if plot.options.file == nil { panel = .plotImage(UUID(), image) } else { plotWritten(image, editor: editor) }
1115                } catch {
1116                    commands.show("\(error)")
1117                }
1118            }
1119            return
1120        }
1121        #endif
1122        if let url = PlotOutput.file(plot, directory: directory) {
1123            guard reach([url.path]) else { return }
1124            do {
1125                try PlotOutput.write(plot, to: url)
1126                plotWritten(url, editor: editor, note: PlotOutput.note(plot))
1127            } catch {
1128                commands.show("\(error)")
1129            }
1130        } else {
1131            do { try PlotOutput.check(plot) } catch { return commands.show("\(error)") }
1132            panel = .plot(UUID(), plot)
1133            if let note = PlotOutput.note(plot) { commands.show(note) }
1134        }
1135    }
1136
1137    /// The image is where `file:` says; a link to it shows it again.
1138    private func plotWritten(_ url: URL, editor: OrgEditor, note: String? = nil) {
1139        commands.show(String(localized: "Plot written to \(url.lastPathComponent)") + (note.map { ". " + $0 } ?? ""))
1140        if editor.showsImages { editor.refreshImages() }
1141    }
1142
1143    /// `org-publish`, `org-publish-all`, `org-publish-current-file` and
1144    /// `org-publish-current-project`, with the projects in config.toml.
1145    private func publish(_ id: String) {
1146        let config = (try? String(contentsOf: UserConfig.file("config.toml"), encoding: .utf8)) ?? ""
1147        let loaded = Publish.projects(fromConfig: config, root: workspace.rootPaths.first)
1148        if let problem = loaded.problems.first { commands.show(problem) }
1149        guard !loaded.projects.isEmpty else { return commands.show(String(localized: "No [[publish]] projects in config.toml")) }
1150        let read = { (path: String) -> String? in session.exportText(of: path) }
1151        let note = session.openPaths.contains(where: session.exportLeavesOut) ? " " + DocumentSession.exportNote : ""
1152        let codeStyle = HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme)
1153        func run(_ chosen: [PublishProject], only: String? = nil) {
1154            // The chosen projects and their components read and write these folders.
1155            let involved = { loaded.projects.filter { project in chosen.contains { $0 == project || $0.components.contains(project.name) } } }
1156            guard reach(involved().flatMap { [$0.baseDirectory, $0.publishingDirectory] }, directories: true) else { return }
1157            do {
1158                let report = try Publish.publish(chosen, all: loaded.projects, only: only, read: read) { function, text, path, bodyOnly in
1159                    try Publish.export(function, text: text, path: path, bodyOnly: bodyOnly, settings: Preferences.orgSettings, codeStyle: codeStyle)
1160                }
1161                commands.show((report.skipped.isEmpty ? String(localized: "Published \(report.published.count) files")
1162                    : String(localized: "Published \(report.published.count) files, \(report.skipped.count) up to date")) + note)
1163            } catch {
1164                commands.show("\(error)")
1165            }
1166        }
1167        let current = session.path.map { Publish.projects(containing: $0, in: loaded.projects) } ?? []
1168        switch id {
1169        case "app.publish.all":
1170            run(loaded.projects)
1171        case "app.publish.current-file":
1172            guard let path = session.path, !current.isEmpty else { return commands.show(String(localized: "File is not part of any known project")) }
1173            run([current[0]], only: path)
1174        case "app.publish.current-project":
1175            guard !current.isEmpty else { return commands.show(String(localized: "File is not part of any known project")) }
1176            run([current[0]])
1177        default:
1178            let names = loaded.projects.map(\.name)
1179            commands.ask(Prompt(key: "project", message: String(localized: "Publish project:"), choices: names)) { answer in
1180                guard let answer, let project = loaded.projects.first(where: { $0.name == answer }) else { return }
1181                run([project])
1182            }
1183        }
1184    }
1185
1186    /// Work a command hands to the platform: tables recalculated in Emacs.
1187    private func runExternal(_ request: ExternalRequest) {
1188        switch request {
1189        case .openLink(let link):
1190            if let message = LinkOpener.open(link, session: session, workspace: workspace, ask: commands.ask, elisp: runElispLink, citation: citationActions.follow) {
1191                commands.show(message)
1192            }
1193            // `org-occur` for a regexp link, once the editor shows the file.
1194            if let regexp = Links.regexpSearch(link) {
1195                DispatchQueue.main.async { commands.editor?.perform(SparseTreeCommand(), answers: ["sparse": "/", "regexp": regexp]) }
1196            }
1197        case .tangle(let scope):
1198            guard ProAccess.shared.allows(.babel), reach(session.tangleFiles(scope)) else { return }
1199            commands.show(session.tangle(scope))
1200        case .agenda(let start, let days):
1201            commands.agendaRequest = (start, days)
1202            openWindow(id: "agenda")
1203        case .editBlock(let edit):
1204            blockEdit = BlockEditRequest(edit: edit)
1205        case .columnView(let view):
1206            panel = .columns(UUID(), view)
1207        #if APPSTORE
1208        case .emacsTable(_, _, _, let reason, _, let formula, let partial):
1209            // The fields written before the formula stay, as Emacs leaves them when a formula fails.
1210            if let partial { commands.editor?.perform(PrecomputedEdit(partial)) }
1211            if reason == TableBlocks.lockedReason {
1212                ProAccess.shared.allows(.babel)
1213                return
1214            }
1215            if let formula {
1216                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"))
1217            } else {
1218                commands.show(String(localized: "This table's formulas can't be calculated here: \(TableReason.localized(reason)).", comment: "Table formulas orgstar can't calculate"))
1219            }
1220        #else
1221        case .emacsTable(let table, let point, let form, let reason, let lisp, let formula, let partial):
1222            // Emacs runs the blocks `org-sbe` names without asking, so they need Babel, and
1223            // the question below each time.
1224            let blocks = reason == TableBlocks.lockedReason || session.document?.text.contains("org-sbe") == true
1225            if blocks, !ProAccess.shared.allows(.babel) {
1226                if let partial { commands.editor?.perform(PrecomputedEdit(partial)) }
1227                return
1228            }
1229            guard EmacsRunner.executable() != nil else {
1230                // Without Emacs this is the App Store build's case: keep the fields written so far.
1231                if let partial { commands.editor?.perform(PrecomputedEdit(partial)) }
1232                if let formula {
1233                    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"))
1234                }
1235                return commands.show(String(localized: "This table's formulas can't be calculated here: \(TableReason.localized(reason)).", comment: "Table formulas orgstar can't calculate"))
1236            }
1237            let run = {
1238                commands.show(String(localized: "Recalculating in Emacs (\(TableReason.localized(reason)))…", comment: "Table formulas sent to Emacs, and why"))
1239                commands.runInEmacs { commands.show(await session.recalculateInEmacs(table: table, point: point, form: form)) }
1240            }
1241            guard lisp, let path = session.path, let text = session.document?.text else { return run() }
1242            let content = (text as NSString).substring(with: NSRange(location: table.lowerBound, length: min((text as NSString).length, table.upperBound + 2000) - table.lowerBound))
1243            if !blocks, trust.isTrusted(path: path, content: content) { return run() }
1244            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)")
1245            commands.ask(Prompt(key: "confirm", message: message, choices: blocks ? ["yes", "no"] : ["yes", "no", "always"])) { answer in
1246                switch answer {
1247                case "always":
1248                    trust.trust(path: path, content: content)
1249                    run()
1250                case "yes": run()
1251                default: commands.show(String(localized: "Not recalculated"))
1252                }
1253            }
1254        #endif
1255        case .babel(let job):
1256            guard ProAccess.shared.allows(.babel) else { return }
1257            let run = {
1258                guard reach(session.resultFile(of: job).map { [$0] } ?? []) else { return }
1259                commands.show(String(localized: "Running \(job.language) block… (⌘. to cancel)"))
1260                session.startBabel(job) { commands.show($0) }
1261            }
1262            guard let path = session.path else { return }
1263            if !job.alwaysAsk, trust.isTrusted(path: path, content: job.blockText) { return run() }
1264            let choices = job.alwaysAsk ? ["yes", "no"] : ["yes", "no", "always"]
1265            commands.ask(Prompt(key: "confirm", message: String(localized: "Run this \(job.language) block? (\(choices.joined(separator: ", ")))"), choices: choices)) { answer in
1266                switch answer {
1267                case "always":
1268                    trust.trust(path: path, content: job.blockText)
1269                    run()
1270                case "yes": run()
1271                default: commands.show(String(localized: "Not run"))
1272                }
1273            }
1274        }
1275    }
1276
1277    /// Runs an `elisp:` link's form once trusted, asking as `org-link-elisp-confirm-function` does.
1278    private func runElispLink(_ form: String) {
1279        let run = { _ = Task { commands.show(await session.evaluateLink(form)) } }
1280        let content = "elisp:" + form
1281        if let path = session.path, trust.isTrusted(path: path, content: content) { return run() }
1282        let choices = session.path == nil ? ["yes", "no"] : ["yes", "no", "always"]
1283        commands.ask(Prompt(key: "confirm", message: String(localized: "Execute \(form) as Elisp? (\(choices.joined(separator: ", ")))"), choices: choices)) { answer in
1284            switch answer {
1285            case "always":
1286                if let path = session.path { trust.trust(path: path, content: content) }
1287                run()
1288            case "yes": run()
1289            default: commands.show(String(localized: "Not run"))
1290            }
1291        }
1292    }
1293
1294    private struct ReminderKey: Equatable {
1295        var enabled: Bool
1296        var lead: Int
1297        var subfolders: Bool
1298        /// The widgets leave out hidden folders.
1299        var hidden: Set<String>
1300        var files: Int
1301        var changed: Int?
1302        var edits: Int
1303        var hour: Int
1304        /// The widgets' colors.
1305        var theme: ThemeSpec
1306    }
1307
1308    /// Sets the notifications for the next week's timed entries, once edits pause.
1309    private func updateReminders() async {
1310        guard let scheduler else { return }
1311        guard remindersEnabled else {
1312            await scheduler.clear()
1313            return
1314        }
1315        guard !Task.isCancelled, !workspace.files.isEmpty else { return }
1316        let agenda = reminderAgenda ?? AgendaModel(workspace: workspace)
1317        reminderAgenda = agenda
1318        agenda.includeSubfolders = agendaSubfolders
1319        agenda.excludeArchives = OrgPreferences.agendaExcludeArchives()
1320        let open = session.openTexts
1321        let reminders = await agenda.reminders(open: open, lead: reminderLead)
1322        guard !Task.isCancelled else { return }
1323        await scheduler.reconcile(reminders)
1324    }
1325
1326    /// The desktop widgets' agenda and habits, written where the widget extension reads them,
1327    /// with the widgets reloaded when they changed; and today's agenda for the menu bar item.
1328    private func updateWidgets() async {
1329        let file = ProAccess.shared.isUnlocked ? AgendaSnapshot.file() : nil
1330        guard !Task.isCancelled, !workspace.files.isEmpty, file != nil || menuBarItem else { return }
1331        let days = widgetAgenda ?? AgendaModel(workspace: workspace)
1332        widgetAgenda = days
1333        days.mode = .agenda(span: AgendaSnapshot.dayCount, startOffset: 0)
1334        days.startOnWeekday = nil
1335        days.includeSubfolders = agendaSubfolders
1336        days.excludeArchives = OrgPreferences.agendaExcludeArchives()
1337        days.hiddenFolders = HiddenFolders.shared.all
1338        days.agendaFiles = OrgPreferences.agendaFiles()
1339        days.options = OrgPreferences.agendaOptions(days.options)
1340        days.options.logMode = false
1341        days.calendarEvents = ProAccess.shared.isUnlocked && OrgPreferences.calendarEvents() && CalendarEvents.isAuthorized ? CalendarAccess.events : nil
1342        days.calendarNames = OrgPreferences.calendarEventCalendars()
1343        days.reminderLists = ProAccess.shared.isUnlocked && OrgPreferences.agendaReminders() && ReminderLists.isAuthorized ? CalendarAccess.reminders : nil
1344        days.reminderListNames = OrgPreferences.agendaReminderLists()
1345        let open = session.openTexts
1346        await days.refresh(open: open)
1347        guard !Task.isCancelled else { return }
1348        let snapshot = AgendaSnapshot(groups: days.groups(), today: days.today, theme: theme, generated: Date())
1349        menuToday = snapshot.days.first.map { $0.overdue + $0.rows } ?? []
1350        guard let file else { return }
1351        if (try? HabitSnapshot(habits: await days.habits(open: open), theme: theme).write()) == true {
1352            WidgetCenter.shared.reloadTimelines(ofKind: "sh.krz.orgstar.habits")
1353        }
1354        if (try? snapshot.write(to: file)) == true { WidgetCenter.shared.reloadAllTimelines() }
1355    }
1356
1357    private func loadKeymap() {
1358        let loaded = KeymapLoader.load(preset, commands: Set(EditorCommands.all.map(\.id)))
1359        keymap = loaded.keymap
1360        commands.keymap = loaded.keymap
1361        commands.modal = preset.isModal
1362        if let first = loaded.problems.first {
1363            commands.show("keymap.toml: " + (loaded.problems.count > 1 ? String(localized: "\(first) (and \(loaded.problems.count - 1) more)") : first))
1364        }
1365    }
1366
1367    /// `SPC b b`: open buffers, most recent first, by name (with the folder when names repeat).
1368    private func switchBuffer() {
1369        let paths = session.recentPaths.dropFirst() + session.recentPaths.prefix(1)
1370        let labels = paths.map(session.bufferName)
1371        guard !labels.isEmpty else { return commands.show(String(localized: "No buffers are open")) }
1372        commands.ask(Prompt(key: "buffer", message: String(localized: "Switch to buffer:"), choices: labels)) { answer in
1373            guard let answer, let index = labels.firstIndex(of: answer) else { return }
1374            session.open(Array(paths)[index])
1375        }
1376    }
1377
1378    /// A file continued from another device, at the caret's heading or line there.
1379    private func continueHandoff(_ place: HandoffPlace) {
1380        let match = place.resolve(roots: workspace.rootPaths)
1381        guard case .file(let path) = match else { return commands.show(place.problem(match) ?? "") }
1382        let offset = session.text(of: path).map { place.offset(in: $0, settings: session.defaults) } ?? 0
1383        commands.jump(path: path, offset: offset)
1384    }
1385
1386    /// Runs a command from a key, the palette or the Org menu.
1387    private func perform(_ id: String) {
1388        if hiddenCommandIDs.contains(id) {
1389            if let replacement = AppStoreCommands.replacement(for: id) { return perform(replacement) }
1390            return commands.show(Self.unavailable(EditorCommands.all.first { $0.id == id }?.title ?? id))
1391        }
1392        if let feature = ProFeature.required(byCommand: id), !ProAccess.shared.allows(feature) { return }
1393        if !session.isOrg, Printing.commands.contains(id) || OrgOnlyCommands.refuses(id, markdown: session.isMarkdown, path: session.path) {
1394            commands.show(String(localized: "Not an org file"))
1395            return
1396        }
1397        switch id {
1398        case "app.save":
1399            if !session.save(), session.conflict != nil { commands.showingConflict = true }
1400        case "app.quit": NSApp.terminate(nil)
1401        case "app.save-all":
1402            if !session.saveAll(), session.conflict != nil { commands.showingConflict = true }
1403        case "app.buffer.switch": switchBuffer()
1404        case "app.buffer.next": session.cycle(1)
1405        case "app.buffer.previous": session.cycle(-1)
1406        case "app.buffer.last": session.showPrevious()
1407        case "app.buffer.kill":
1408            if let window = paneWindow, window.paneCount > 1 {
1409                window.closeTab(session.path, in: window.focusedPane, commands: commands)
1410            } else if let path = session.path {
1411                if UnsavedChanges.resolve(session) { session.kill(path) }
1412            } else {
1413                NSApp.keyWindow?.performClose(nil)
1414            }
1415        case "app.buffer.kill-others":
1416            let others = session.openPaths.filter { $0 != session.path }
1417            if UnsavedChanges.resolve(session, paths: others) { others.forEach(session.kill) }
1418        case "app.buffer.kill-all":
1419            let all = session.openPaths
1420            if UnsavedChanges.resolve(session, paths: all) { all.forEach(session.kill) }
1421        case "app.toggle-tab-bar": showTabBar.toggle()
1422        case "app.split-below": paneWindow?.split(.vertical)
1423        case "app.split-right": paneWindow?.split(.horizontal)
1424        case "app.pane-close":
1425            guard let window = paneWindow, window.paneCount > 1 else { return commands.show(String(localized: "This is the only pane.", comment: "Close Pane with one pane")) }
1426            commands.store.releasePane(window.focused)
1427            window.close(window.focused)
1428            focusPane(window)
1429        case "app.pane-only":
1430            guard let window = paneWindow else { return }
1431            for id in window.layout.panes where id != window.focused { commands.store.releasePane(id) }
1432            window.closeOthers()
1433            focusPane(window)
1434        case "app.pane-next":
1435            guard let window = paneWindow else { return }
1436            window.focusNext()
1437            focusPane(window)
1438        case "app.window-new": openWindow(id: "editor")
1439        case "app.babel.cancel":
1440            if session.isRunningBabel {
1441                session.cancelBabel()
1442            } else if let task = commands.emacsTask {
1443                task.cancel()
1444            } else {
1445                commands.show(String(localized: "Nothing is running"))
1446            }
1447        case "app.toggle-outline": toggleOutline()
1448        case "app.toggle-backlinks": backlinksShown.toggle()
1449        case "app.toggle-inspector": inspectorShown.toggle()
1450        case "app.toggle-markup": showMarkup.toggle()
1451        case "app.toggle-line-numbers": showLineNumbers.toggle()
1452        case "app.import-emacs": showingImport = true
1453        case "app.import-markdown": markdownImport = .markdown
1454        case "app.import-obsidian": markdownImport = .obsidian
1455        case "app.new-file-from-template": showingTemplate = true
1456        case "app.replace-in-files", "app.rename-tag", "app.rename-todo-keyword":
1457            replacing = ReplaceKind(command: id).map { ($0, replaceInitial(for: $0)) }
1458        case "app.edit-config": commands.jump(path: UserConfig.configFile.path, offset: 0)
1459        case "app.quick-open": commands.showingQuickOpen = true
1460        case "app.palette": commands.showingPalette = true
1461        case "app.messages": commands.showingMessages = true
1462        case "app.search": commands.focusSearch = true
1463        case "app.reload-keymap":
1464            loadKeymap()
1465            commands.show(String(localized: "Keymap reloaded"))
1466        case "app.refile", "app.refile.copy":
1467            let keep = id == "app.refile.copy"
1468            let targets = workspace.refileTargets(openPath: session.path, document: session.document)
1469            commands.ask(Prompt(key: "refile", message: keep ? String(localized: "Copy to:") : String(localized: "Refile to:"), choices: targets.map(\.label))) { answer in
1470                guard let answer else { return }
1471                if let target = targets.first(where: { $0.label == answer }) {
1472                    if let message = session.refile(to: target, keep: keep) { commands.show(message) }
1473                    return
1474                }
1475                // `org-refile-allow-creating-parent-nodes`: `parent/new` adds the heading first.
1476                let creating = OrgPreferences.refileSettings().creating
1477                guard creating != .no, let (parent, child) = RefileSettings.newNode(answer, in: targets) else { return commands.show(String(localized: "Invalid target location")) }
1478                let create = {
1479                    switch session.createRefileChild(under: parent, title: child) {
1480                    case .success(let target): if let message = session.refile(to: target, keep: keep) { commands.show(message) }
1481                    case .failure(.message(let message)): commands.show(message)
1482                    }
1483                }
1484                guard creating == .confirm else { return create() }
1485                commands.ask(Prompt(key: "confirm", message: String(localized: "Create new node \"\(child)\"?"), choices: ["yes", "no"])) { reply in
1486                    if reply == "yes" { create() }
1487                }
1488            }
1489        case "app.refile.goto":
1490            // `C-u C-c C-w`: the target heading, or the end of a file.
1491            let targets = workspace.refileTargets(openPath: session.path, document: session.document)
1492            commands.ask(Prompt(key: "refile", message: String(localized: "Goto:"), choices: targets.map(\.label))) { answer in
1493                guard let answer, let target = targets.first(where: { $0.label == answer }) else { return }
1494                commands.jump(path: target.path, offset: target.start ?? Int.max)
1495            }
1496        case "app.archive":
1497            guard reach(session.archiveFile().map { [$0] } ?? []) else { return }
1498            if let message = session.archive() { commands.show(message) }
1499        case "app.table-import":
1500            // `org-table-import`: a TSV, CSV or space-separated file becomes a table at point.
1501            guard let editor = commands.editor else { return commands.show(String(localized: "No file is open")) }
1502            let panel = NSOpenPanel()
1503            panel.allowedContentTypes = [.commaSeparatedText, .tabSeparatedText, .plainText]
1504            guard panel.runModal() == .OK, let url = panel.url else { return }
1505            guard let contents = try? String(contentsOf: url, encoding: .utf8) else { return commands.show(String(localized: "Can't read \(url.lastPathComponent)")) }
1506            editor.perform(ImportTable(contents: contents))
1507        case "app.table-export":
1508            // `org-table-export`: CSV for a .csv name, else TSV.
1509            guard let editor = commands.editor else { return commands.show(String(localized: "No file is open")) }
1510            let context = editor.context()
1511            guard ImportTable.exportText(context.text, at: context.caret, path: "") != nil else { return commands.show(String(localized: "No table at point")) }
1512            let panel = NSSavePanel()
1513            panel.nameFieldStringValue = "table.csv"
1514            guard panel.runModal() == .OK, let url = panel.url,
1515                  let text = ImportTable.exportText(context.text, at: context.caret, path: url.path) else { return }
1516            do {
1517                try text.write(to: url, atomically: true, encoding: .utf8)
1518                commands.show(String(localized: "Export done."))
1519            } catch {
1520                commands.show(String(localized: "File not written: \(error.localizedDescription)"))
1521            }
1522        case "org.subtree.paste":
1523            guard let text = NSPasteboard.general.string(forType: .string) else { return commands.show(String(localized: "The clipboard is empty")) }
1524            commands.editor?.perform(PasteSubtree(text: text))
1525        case "org.link.insert":
1526            commands.editor?.perform(InsertLink(stored: commands.storedLinks, file: session.path))
1527        case "org.link.store":
1528            guard let editor = commands.editor, let path = session.path else { return commands.show(String(localized: "No method for storing a link from this buffer")) }
1529            let context = editor.context()
1530            let denote = OrgPreferences.usesDenote() ? Links.storeDenote(in: context, path: path) : nil
1531            commands.storeLink(denote ?? Links.store(in: context, path: Links.abbreviate(path, home: OrgPaths.home)))
1532        case "org.id.store-link":
1533            guard let editor = commands.editor, let path = session.path else { return }
1534            if case .commit = editor.perform(CreateID()),
1535               let link = Links.storeID(in: editor.context(), fileName: (path as NSString).lastPathComponent) {
1536                commands.storeLink(link)
1537            }
1538        case "app.agenda":
1539            openWindow(id: "agenda")
1540        case "app.clock.in":
1541            clockIn(.caret)
1542        case "app.clock.in-recent":
1543            clockIn(.select)
1544        case "app.clock.in-last":
1545            clockIn(.last)
1546        case let id where id.hasPrefix("app.clock.history."):
1547            if let index = Int(id.dropFirst("app.clock.history.".count)), index < clock.history.count { clockIn(.task(clock.history[index])) }
1548        case "app.clock.out":
1549            commands.show(clock.clockOut(session))
1550        case "app.clock.cancel":
1551            commands.show(clock.clockOut(session, cancel: true))
1552        case "app.clock.goto":
1553            let found = clock.goto(session)
1554            if let location = found.location { commands.jump(path: location.path, offset: location.offset) }
1555            if let message = found.message { commands.show(message) }
1556        case "app.clock.goto-recent":
1557            Task {
1558                let found = await clock.gotoRecent(session, ask: askClock)
1559                if let location = found.location { commands.jump(path: location.path, offset: location.offset) }
1560                if let message = found.message { commands.show(message) }
1561            }
1562        case "app.clock.default":
1563            commands.show(clock.markDefault(session))
1564        case "app.clock.resolve":
1565            Task { report(await clock.resolveOpenClocks(session, paths: orgFiles, ask: askClock)) }
1566        case "app.clock.report":
1567            openWindow(id: "clock-report")
1568        case "app.board":
1569            openWindow(id: "board")
1570        case "app.node.graph":
1571            openWindow(id: "graph")
1572        case "app.sidebar-agenda":
1573            sidebarAgenda.toggle()
1574        case "app.capture":
1575            NSApp.activate()
1576            openWindow(id: "capture")
1577        case "app.revert":
1578            // `:e`: the file as it is on disk; unsaved changes go to recovery.
1579            guard session.path != nil else { return commands.show(String(localized: "No file is open")) }
1580            session.useDiskVersion()
1581            commands.show(String(localized: "Reverted to the file on disk"))
1582        case "app.sync-conflicts":
1583            guard session.path != nil else { return commands.show(String(localized: "No file is open")) }
1584            panel = .syncCopies(UUID())
1585        case "app.recovery":
1586            guard session.path != nil else { return commands.show(String(localized: "No file is open")) }
1587            panel = .recovery(UUID())
1588        case "app.lint":
1589            guard session.path != nil else { return commands.show(String(localized: "No file is open")) }
1590            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")) }
1591            lintShown = true
1592            lintRun += 1
1593        case "app.lint-folders":
1594            commands.folderLint.run(workspace: workspace, session: session)
1595            openWindow(id: "lint-folders")
1596        case "app.copy-rich-text":
1597            copyRichText()
1598        case "app.print", "app.print-subtree", "app.print-selection":
1599            printFile(id)
1600        case "app.print-agenda":
1601            commands.agendaPrintRequested = true
1602            openWindow(id: "agenda")
1603        case "app.share-subtree":
1604            guard let path = session.path else { return commands.show(String(localized: "No file is open")) }
1605            if let refusal = session.refusesSubtreeShare(path, at: session.caret) { return commands.show(refusal) }
1606            guard let share = session.subtreeShare(path, at: session.caret) else { return commands.show(String(localized: "Not in a subtree")) }
1607            panel = .shareSubtree(UUID(), share)
1608        case "app.export-dialog":
1609            guard let path = session.path else { return commands.show(String(localized: "No file is open")) }
1610            panel = .export(UUID(), URL(fileURLWithPath: path))
1611        case "app.export-subtree", "app.export-body-only":
1612            guard let path = session.path else { return commands.show(String(localized: "No file is open")) }
1613            var settings = ExportSettings.saved(for: path)
1614            if id == "app.export-subtree" {
1615                settings.subtree.toggle()
1616                commands.show(settings.subtree ? String(localized: "Export commands: subtree at the caret") : String(localized: "Export commands: whole file"))
1617            } else {
1618                settings.bodyOnly.toggle()
1619                commands.show(settings.bodyOnly ? String(localized: "Export commands: body only") : String(localized: "Export commands: whole document"))
1620            }
1621            settings.save(for: path)
1622        case let id where id.hasPrefix("app.export."):
1623            let format = String(id.dropFirst("app.export.".count))
1624            guard let options = (session.path.map { ExportSettings.saved(for: $0) } ?? ExportSettings()).commandOptions(format) else {
1625                return commands.show(ExportSettings.noBodyOnly)
1626            }
1627            export(format, subtree: options.subtree, bodyOnly: options.bodyOnly)
1628        case let id where id.hasPrefix("app.publish"):
1629            publish(id)
1630        case "app.plot":
1631            plotTable()
1632        case let id where id.hasPrefix("app.crypt."):
1633            crypt(id)
1634        case let id where id.hasPrefix("app.attach."):
1635            guard reach(attachActions.entry().flatMap { Attachments.directory($0, noFSCheck: true) }.map { [$0] } ?? [], directories: true) else { return }
1636            attachActions.run(id)
1637        case "app.node.protocol":
1638            guard let request = commands.roamProtocol else { return }
1639            commands.roamProtocol = nil
1640            roamActions.follow(request)
1641        case let id where id.hasPrefix("app.dailies.") || id.hasPrefix("app.node."):
1642            roamActions.run(id)
1643        case "app.cite.insert":
1644            citationActions.insert()
1645        default:
1646            if let editor = commands.editor { editor.run(id) } else { commands.show(String(localized: "No file is open")) }
1647        }
1648    }
1649
1650    private var askClock: ClockModel.Ask { commands.askClock }
1651
1652    /// The files `org-resolve-clocks` looks through: the workspace's org files.
1653    private var orgFiles: [String] { workspace.files.filter { $0.kind == .org }.map(\.path) }
1654
1655    private func clockIn(_ target: ClockModel.Target) {
1656        Task { report(await clock.clockIn(session, target: target, paths: orgFiles, ask: askClock)) }
1657    }
1658
1659    /// The last message of a clock command, and the clock to show for `j`.
1660    private func report(_ outcome: ClockModel.Outcome) {
1661        if let jump = outcome.jump { commands.jump(path: jump.path, offset: jump.offset) }
1662        if let message = outcome.messages.last(where: { !$0.isEmpty }) { commands.show(message) }
1663    }
1664
1665    /// What failed, for the error alert's title.
1666    private var errorTitle: String {
1667        (workspace.lastError != nil ? workspace.lastErrorTitle : session.lastErrorTitle) ?? "orgstar"
1668    }
1669
1670    private var errorShown: Binding<Bool> {
1671        Binding(get: { workspace.lastError != nil || session.lastError != nil }, set: { _ in })
1672    }
1673}
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