Sources/Orgstar/ContentView.swift

6e84c5315a776376ffe643f78b5b48551895d250
orgstar/Sources/Orgstar/ContentView.swift

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