Sources/Orgstar/ContentView.swift

d56fe8ddca3a5799ae51e521cbb0ee1c4e3af9a5
orgstar/Sources/Orgstar/ContentView.swift

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