Sources/Orgstar/ContentView.swift

5ab870e0abd4140b7b83076712bf63910aaa4ec0
orgstar/Sources/Orgstar/ContentView.swift

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