Sources/Orgstar/ContentView.swift

be996c163c7399849cca3987b604bf1f64a98962
orgstar/Sources/Orgstar/ContentView.swift

1668 lines · 95533 bytes

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