Sources/Orgstar/ContentView.swift

0adc91d2a0fc5b932e8b3865ffd452325e5d86d0
orgstar/Sources/Orgstar/ContentView.swift

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