Sources/Orgstar/ContentView.swift

53dc6c6bfdccaa724b05a834545373663c5cdee0
orgstar/Sources/Orgstar/ContentView.swift

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