Sources/Orgstar/ContentView.swift

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