Sources/Orgstar/ContentView.swift

913aa7e847d0b1f4559e14e65b313fa805337f30
orgstar/Sources/Orgstar/ContentView.swift

1394 lines · 76655 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 "latex" where exportLaTeX(text, whole: whole, url: url, to: destination, open: open, subtree: subtree ? caret : nil, bodyOnly: bodyOnly, settings: defaults):
 632            break
 633        case "print-pdf", "docx", "rtf", "plain-text":
 634            let ext = ["print-pdf": "pdf", "plain-text": "txt"][format] ?? format
 635            let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
 636            guard let target = destination ?? writable(ExportScope.output(for: url, name: name, extension: ext)) else { return }
 637            let html = HTMLExport.page(
 638                text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path,
 639                codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme), language: OrgPreferences.exportLanguage()
 640            )
 641            let directory = url.deletingLastPathComponent()
 642            // Images that can't be read are left out, so offer access to them first.
 643            _ = reach(PDFExport.imageFiles(html, directory: directory).filter(WorkspaceModel.isThere))
 644            if format == "print-pdf" { commands.show("Exporting to PDF…") }
 645            Task {
 646                do {
 647                    let data: Data
 648                    switch format {
 649                    case "print-pdf": data = try await PDFExport.pdf(html: html, directory: directory, options: OrgPreferences.pdfOptions())
 650                    case "docx": data = try RichTextExport.docx(html: html, directory: directory)
 651                    case "rtf": data = try RichTextExport.rtf(RichTextExport.attributed(html: html, directory: directory))
 652                    default: data = Data(RichTextExport.plain(try RichTextExport.attributed(html: html, directory: directory)).utf8)
 653                    }
 654                    try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
 655                    try data.write(to: target, options: .atomic)
 656                    commands.show("Exported to \(target.lastPathComponent)")
 657                    if open { NSWorkspace.shared.open(target) }
 658                } catch {
 659                    commands.show("Can't export \(target.lastPathComponent): \(error)")
 660                }
 661            }
 662        default:
 663            #if !APPSTORE
 664            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"]
 665            guard let function = functions[format] else { return }
 666            commands.show("Exporting with Emacs…")
 667            commands.runInEmacs {
 668                do {
 669                    // Emacs narrows to the subtree and reads EXPORT_FILE_NAME itself.
 670                    let point = subtree ? (whole as NSString).substring(to: min(caret, (whole as NSString).length)).unicodeScalars.count + 1 : nil
 671                    var written = URL(fileURLWithPath: try await EmacsRunner.export(
 672                        text: whole, path: path, function: function, subtree: point, bodyOnly: bodyOnly
 673                    ))
 674                    if let destination, destination.standardizedFileURL != written.standardizedFileURL {
 675                        try? FileManager.default.removeItem(at: destination)
 676                        try FileManager.default.moveItem(at: written, to: destination)
 677                        written = destination
 678                    }
 679                    commands.show("Exported to \(written.lastPathComponent)")
 680                    if open { NSWorkspace.shared.open(written) }
 681                } catch is CancellationError {
 682                    commands.show("Export canceled")
 683                } catch {
 684                    commands.show("\(error)")
 685                }
 686            }
 687            #else
 688            let title = EditorCommands.all.first { $0.id == "app.export." + format }?.title
 689            commands.show(Self.unavailable(title ?? format))
 690            #endif
 691        }
 692    }
 693
 694    /// Writes `text` as LaTeX, as ox-latex does. False when the native export can't match Emacs
 695    /// and Emacs is installed to export instead; otherwise the reason is shown.
 696    private func exportLaTeX(_ text: String, whole: String, url: URL, to destination: URL?, open: Bool, subtree: Int?, bodyOnly: Bool, settings: OrgSettings) -> Bool {
 697        let content: String
 698        do {
 699            content = try LaTeXExport.document(text, settings: settings, path: url.path, bodyOnly: bodyOnly, author: NSFullUserName(), language: OrgPreferences.exportLanguage(), file: true)
 700        } catch {
 701            #if !APPSTORE
 702            if EmacsRunner.executable() != nil { return false }
 703            #endif
 704            commands.show("Can't export to LaTeX: \(error.localizedDescription)")
 705            return true
 706        }
 707        let name = ExportScope.fileName(whole, subtreeAt: subtree, settings: settings)
 708        guard let target = destination ?? writable(ExportScope.output(for: url, name: name, extension: "tex")) else { return true }
 709        do {
 710            try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
 711            try content.write(to: target, atomically: true, encoding: .utf8)
 712            commands.show("Exported to \(target.lastPathComponent)")
 713            if open { NSWorkspace.shared.open(target) }
 714        } catch {
 715            commands.show("Can't write \(target.lastPathComponent): \(error.localizedDescription)")
 716        }
 717        return true
 718    }
 719
 720    /// `url`; in the App Store build, when the sandbox keeps orgstar out of its folder, `url` once
 721    /// that folder is granted, or where a save panel puts it instead. Nil when canceled.
 722    private func writable(_ url: URL) -> URL? {
 723        #if APPSTORE
 724        guard let folder = workspace.foldersToGrant(for: [url.path]).first else { return url }
 725        let elsewhere = String(localized: "Save Elsewhere…", comment: "Button that asks where an export goes instead")
 726        switch GrantAccess.ask(folder, workspace: workspace, alternative: elsewhere) {
 727        case .granted: return url
 728        case .canceled: return nil
 729        case .alternative: break
 730        }
 731        let panel = NSSavePanel()
 732        panel.directoryURL = url.deletingLastPathComponent()
 733        panel.nameFieldStringValue = url.lastPathComponent
 734        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")
 735        return panel.runModal() == .OK ? panel.url : nil
 736        #else
 737        return url
 738        #endif
 739    }
 740
 741    private func saveBuffers() {
 742        #if APPSTORE
 743        BufferRestore.save(session, workspace: workspace)
 744        #else
 745        BufferRestore.save(session)
 746        #endif
 747    }
 748
 749    /// In the App Store build, asks for the folders outside the sidebar's folders that `paths`
 750    /// need. False when one is still out of reach.
 751    private func reach(_ paths: @autoclosure () -> [String], directories: Bool = false) -> Bool {
 752        #if APPSTORE
 753        GrantAccess.reach(paths(), directories: directories, workspace: workspace)
 754        #else
 755        true
 756        #endif
 757    }
 758
 759    /// In the App Store build, offers access to the setup files and includes of `text` that
 760    /// can't be read. False, with a message, when an include still can't be read, rather than
 761    /// exporting it as an empty line.
 762    private func readsIncludes(_ text: String, path: String) -> Bool {
 763        #if APPSTORE
 764        let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
 765        var setupFiles: [String] = []
 766        _ = Preferences.orgSettings.resolvingSetupFiles(in: text, path: path) { file in
 767            let contents = OrgSettings.readFile(file)
 768            if contents == nil, WorkspaceModel.isThere(file) { setupFiles.append(file) }
 769            return contents
 770        }
 771        let includes = ExportPreprocess.unreadableIncludes(text, directory: directory).filter(WorkspaceModel.isThere)
 772        guard !(setupFiles + includes).isEmpty else { return true }
 773        _ = reach(setupFiles + includes)
 774        guard let unreadable = ExportPreprocess.unreadableIncludes(text, directory: directory).first else { return true }
 775        commands.show(String(localized: "Can't include \(OrgPaths.abbreviatingWithTilde(unreadable)).", comment: "Export stopped by an #+INCLUDE file that can't be read"))
 776        return false
 777        #else
 778        return true
 779        #endif
 780    }
 781
 782    /// Says a command doesn't run in this build.
 783    static func unavailable(_ title: String) -> String {
 784        String(localized: "\(CommandTitle.localized(title)) isn't available.", comment: "A command the Mac App Store build leaves out")
 785    }
 786
 787    /// `org-icalendar-export-agenda-files`, or with `combined`, `org-icalendar-combine-agenda-files`.
 788    private func exportAgendaCalendars(combined: Bool) {
 789        let paths = workspace.agendaFilePaths()
 790        guard reach(paths + (combined ? [OrgPreferences.icalendarCombinedFile()] : [])) else { return }
 791        let read = { (path: String) -> (text: String, settings: OrgSettings)? in
 792            guard let text = session.openDocuments.first(where: { $0.path == path })?.document.text ?? (try? String(contentsOfFile: path, encoding: .utf8)) else { return nil }
 793            return (text, Preferences.orgSettings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile))
 794        }
 795        do {
 796            let options = OrgPreferences.icalendarOptions()
 797            if combined {
 798                let url = try ICalendarFiles.combine(paths, to: OrgPreferences.icalendarCombinedFile(), options: options, read: read)
 799                commands.show("Exported \(paths.count) agenda files to \(url.lastPathComponent)")
 800            } else {
 801                let written = try ICalendarFiles.exportEach(paths, options: options, read: read)
 802                commands.show("Exported \(written.count) agenda files to iCalendar")
 803            }
 804        } catch {
 805            commands.show("Can't export: \(error.localizedDescription)")
 806        }
 807    }
 808
 809    /// org-crypt's commands at the caret, through the passphrase sheet.
 810    private func crypt(_ id: String) {
 811        guard let editor = commands.editor, let path = session.path else { return commands.show("No file is open") }
 812        let caret = editor.context().caret
 813        let text = editor.context().text
 814        switch id {
 815        case "app.crypt.forget-passphrase":
 816            CryptPassphrases.forget(path)
 817            commands.show("Passphrase forgotten for \((path as NSString).lastPathComponent)")
 818        case "app.crypt.encrypt-entries":
 819            panel = .crypt(UUID(), CryptRequest(mode: .encryptAll(tag: OrgPreferences.cryptTag()), path: path, offset: caret))
 820        default:
 821            guard OrgCrypt.heading(text, at: caret) != nil else { return commands.show("Before first headline") }
 822            if id == "app.crypt.encrypt-entry" {
 823                guard OrgCrypt.encryptedRange(text, at: caret) == nil else { return commands.show("The entry is encrypted already") }
 824                panel = .crypt(UUID(), CryptRequest(mode: .encrypt, path: path, offset: caret))
 825            } else {
 826                guard OrgCrypt.encryptedRange(text, at: caret) != nil else { return commands.show("Not an encrypted entry") }
 827                panel = .crypt(UUID(), CryptRequest(mode: id == "app.crypt.open-entry" ? .open : .decryptInPlace, path: path, offset: caret))
 828            }
 829        }
 830    }
 831
 832    /// org-roam's daily notes and nodes.
 833    private var roamActions: RoamActions {
 834        var actions = RoamActions(
 835            session: session, roots: { [workspace] in workspace.rootPaths },
 836            nodes: { [workspace, session] in workspace.nodes(overlay: workspace.overlay(session.openDocuments)) },
 837            show: { [commands] in commands.show($0) }, ask: { [commands] in commands.ask($0, reply: $1) },
 838            open: { [commands] path, offset in commands.jump(path: path, offset: offset) },
 839            insertLink: { [commands] link, title in
 840                guard let editor = commands.editor else { return commands.show("No file is open") }
 841                let context = editor.context()
 842                let range = context.selection.first ?? context.caret..<context.caret
 843                let selected = (context.text as NSString).substring(with: NSRange(range))
 844                let text = Links.makeString(link, selected.isEmpty ? title : selected)
 845                let end = range.lowerBound + (text as NSString).length
 846                editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: [TextEdit(range: range, replacement: text)], selection: [end..<end])))
 847            },
 848            refresh: { [workspace] in Task { await workspace.refresh() } })
 849        #if APPSTORE
 850        actions.reachFolders = { [workspace] in GrantAccess.reach($0, directories: true, workspace: workspace) }
 851        #endif
 852        return actions
 853    }
 854
 855    /// org-attach's commands for the entry at the caret.
 856    private var attachActions: AttachActions {
 857        AttachActions(
 858            entry: { [commands, session] in
 859                guard let editor = commands.editor, let path = session.path else { return nil }
 860                let context = editor.context()
 861                return Attachments.Entry(text: context.text, offset: context.caret, path: path, options: context.options)
 862            },
 863            apply: { applyText($0, caret: $1) }, show: { [commands] in commands.show($0) }, ask: { [commands] in commands.ask($0, reply: $1) },
 864            storeLink: { [commands] in _ = StoredLink.add($0, to: &commands.storedLinks) },
 865            open: { [session, workspace, commands] file in
 866                if let message = LinkOpener.open(OrgLink(type: "file", path: file, raw: "file:" + file), session: session, workspace: workspace, ask: commands.ask) { commands.show(message) }
 867            },
 868            reveal: { NSWorkspace.shared.open(URL(fileURLWithPath: $0, isDirectory: true)) },
 869            pick: { method in
 870                let panel = NSOpenPanel()
 871                panel.canChooseDirectories = true
 872                panel.allowsMultipleSelection = true
 873                panel.message = "File to keep as an attachment"
 874                guard panel.runModal() == .OK else { return }
 875                #if APPSTORE
 876                // The sandbox can remove only files in the sidebar's folders, and links nothing.
 877                if method == .mv, let outside = panel.urls.first(where: { !workspace.contains($0) }) {
 878                    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"))
 879                }
 880                guard method == .cp || method == .mv else { return }
 881                #endif
 882                attachActions.attach(panel.urls, method: method)
 883            })
 884    }
 885
 886    /// The sheet a panel shows.
 887    @ViewBuilder
 888    private func panelView(_ panel: Panel) -> some View {
 889        switch panel {
 890        case .columns(_, let view):
 891            ColumnViewSheet(view: view, run: runInColumnView, document: { session.document.map { ($0.text, $0.tree) } }) { offset in
 892                commands.editor?.reveal(offset)
 893            }
 894        case .export(_, let source):
 895            ExportSheet(source: source, inSubtree: exportSubtreeAvailable, target: exportTarget) { format, destination, open, subtree, bodyOnly in
 896                export(format, to: destination, open: open, subtree: subtree, bodyOnly: bodyOnly)
 897            }
 898        case .plot(_, let plot):
 899            PlotSheet(content: .chart(plot))
 900        case .plotImage(_, let url):
 901            PlotSheet(content: .image(url))
 902        case .crypt(_, let request):
 903            CryptSheet(request: request, text: { session.document?.text ?? "" }, apply: { applyText($0) }) { message in
 904                self.panel = nil
 905                if let message { commands.show(message) }
 906            }
 907        case .conflict:
 908            ConflictSheet(session: session)
 909        case .syncCopies:
 910            SyncConflictSheet(session: session) { commands.show($0) }
 911        case .recovery:
 912            RecoverySheet(session: session) { commands.show($0) }
 913        }
 914    }
 915
 916    /// `new` in place of the buffer's text, as one edit, with the caret at `caret` or where it was.
 917    private func applyText(_ new: String, caret: Int? = nil) {
 918        guard let editor = commands.editor else { return }
 919        let context = editor.context()
 920        let caret = min(caret ?? context.caret, (new as NSString).length)
 921        editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
 922    }
 923
 924    /// `org-plot/gnuplot` for the table at the caret: through gnuplot when it's installed, as
 925    /// Emacs runs it, else drawn here; written to `file:` when the options name one, else shown.
 926    private func plotTable() {
 927        guard let editor = commands.editor, let path = session.path else { return commands.show("No file is open") }
 928        let context = editor.context()
 929        let plot: TablePlot.Plot
 930        do { plot = try TablePlot.plot(context.text, at: context.caret) } catch { return commands.show("\(error)") }
 931        let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
 932        #if !APPSTORE
 933        if let gnuplot = PlotOutput.gnuplot {
 934            commands.show("Plotting with gnuplot…")
 935            Task {
 936                do {
 937                    let image = try await PlotOutput.runGnuplot(plot, directory: directory, gnuplot: gnuplot)
 938                    if plot.options.file == nil { panel = .plotImage(UUID(), image) } else { plotWritten(image, editor: editor) }
 939                } catch {
 940                    commands.show("\(error)")
 941                }
 942            }
 943            return
 944        }
 945        #endif
 946        if let url = PlotOutput.file(plot, directory: directory) {
 947            guard reach([url.path]) else { return }
 948            do {
 949                try PlotOutput.write(plot, to: url)
 950                plotWritten(url, editor: editor)
 951            } catch {
 952                commands.show("\(error)")
 953            }
 954        } else {
 955            panel = .plot(UUID(), plot)
 956        }
 957    }
 958
 959    /// The image is where `file:` says; a link to it shows it again.
 960    private func plotWritten(_ url: URL, editor: OrgEditor) {
 961        commands.show("Plot written to \(url.lastPathComponent)")
 962        if editor.showsImages { editor.refreshImages() }
 963    }
 964
 965    /// `org-publish`, `org-publish-all`, `org-publish-current-file` and
 966    /// `org-publish-current-project`, with the projects in config.toml.
 967    private func publish(_ id: String) {
 968        let config = (try? String(contentsOf: UserConfig.file("config.toml"), encoding: .utf8)) ?? ""
 969        let loaded = Publish.projects(fromConfig: config, root: workspace.rootPaths.first)
 970        if let problem = loaded.problems.first { commands.show(problem) }
 971        guard !loaded.projects.isEmpty else { return commands.show("No [[publish]] projects in config.toml") }
 972        let read = { (path: String) -> String? in
 973            session.openDocuments.first { $0.path == path }?.document.text ?? (try? String(contentsOfFile: path, encoding: .utf8))
 974        }
 975        let codeStyle = HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme)
 976        func run(_ chosen: [PublishProject], only: String? = nil) {
 977            // The chosen projects and their components read and write these folders.
 978            let involved = { loaded.projects.filter { project in chosen.contains { $0 == project || $0.components.contains(project.name) } } }
 979            guard reach(involved().flatMap { [$0.baseDirectory, $0.publishingDirectory] }, directories: true) else { return }
 980            do {
 981                let report = try Publish.publish(chosen, all: loaded.projects, only: only, read: read) { function, text, path, bodyOnly in
 982                    let settings = Preferences.orgSettings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
 983                    if function == "org-md-publish-to-md" { return MarkdownExport.document(text, settings: settings, path: path, bodyOnly: bodyOnly) }
 984                    if function == "org-latex-publish-to-latex" {
 985                        return try LaTeXExport.document(text, settings: settings, path: path, bodyOnly: bodyOnly, author: NSFullUserName(), language: OrgPreferences.exportLanguage(), file: true)
 986                    }
 987                    let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
 988                    return HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, bodyOnly: bodyOnly, codeStyle: codeStyle, language: OrgPreferences.exportLanguage())
 989                }
 990                commands.show("Published \(report.published.count) files" + (report.skipped.isEmpty ? "" : ", \(report.skipped.count) up to date"))
 991            } catch {
 992                commands.show("\(error)")
 993            }
 994        }
 995        let current = session.path.map { Publish.projects(containing: $0, in: loaded.projects) } ?? []
 996        switch id {
 997        case "app.publish.all":
 998            run(loaded.projects)
 999        case "app.publish.current-file":
1000            guard let path = session.path, !current.isEmpty else { return commands.show("File is not part of any known project") }
1001            run([current[0]], only: path)
1002        case "app.publish.current-project":
1003            guard !current.isEmpty else { return commands.show("File is not part of any known project") }
1004            run([current[0]])
1005        default:
1006            let names = loaded.projects.map(\.name)
1007            commands.ask(Prompt(key: "project", message: "Publish project:", choices: names)) { answer in
1008                guard let answer, let project = loaded.projects.first(where: { $0.name == answer }) else { return }
1009                run([project])
1010            }
1011        }
1012    }
1013
1014    /// Work a command hands to the platform: tables recalculated in Emacs.
1015    private func runExternal(_ request: ExternalRequest) {
1016        switch request {
1017        case .openLink(let link):
1018            if let message = LinkOpener.open(link, session: session, workspace: workspace, ask: commands.ask) { commands.show(message) }
1019            // `org-occur` for a regexp link, once the editor shows the file.
1020            if let regexp = Links.regexpSearch(link) {
1021                DispatchQueue.main.async { commands.editor?.perform(SparseTreeCommand(), answers: ["sparse": "/", "regexp": regexp]) }
1022            }
1023        case .tangle(let scope):
1024            guard ProAccess.shared.allows(.babel), reach(session.tangleFiles(scope)) else { return }
1025            commands.show(session.tangle(scope))
1026        case .agenda(let start, let days):
1027            commands.agendaRequest = (start, days)
1028            openWindow(id: "agenda")
1029        case .editBlock(let edit):
1030            blockEdit = BlockEditRequest(edit: edit)
1031        case .columnView(let view):
1032            panel = .columns(UUID(), view)
1033        #if APPSTORE
1034        case .emacsTable(_, _, _, let reason, _):
1035            commands.show(String(localized: "This table's formulas can't be calculated here: \(TableReason.localized(reason)).", comment: "Table formulas orgstar can't calculate"))
1036        #else
1037        case .emacsTable(let table, let point, let form, let reason, let lisp):
1038            let run = {
1039                commands.show(String(localized: "Recalculating in Emacs (\(TableReason.localized(reason)))…", comment: "Table formulas sent to Emacs, and why"))
1040                commands.runInEmacs { commands.show(await session.recalculateInEmacs(table: table, point: point, form: form)) }
1041            }
1042            guard lisp, let path = session.path, let text = session.document?.text else { return run() }
1043            let content = (text as NSString).substring(with: NSRange(location: table.lowerBound, length: min((text as NSString).length, table.upperBound + 2000) - table.lowerBound))
1044            if trust.isTrusted(path: path, content: content) { return run() }
1045            commands.ask(Prompt(key: "confirm", message: "This table's formulas run Lisp. Run them? (yes, no, always)", choices: ["yes", "no", "always"])) { answer in
1046                switch answer {
1047                case "always":
1048                    trust.trust(path: path, content: content)
1049                    run()
1050                case "yes": run()
1051                default: commands.show("Not recalculated")
1052                }
1053            }
1054        #endif
1055        case .babel(let job):
1056            guard ProAccess.shared.allows(.babel) else { return }
1057            let run = {
1058                guard reach(session.resultFile(of: job).map { [$0] } ?? []) else { return }
1059                commands.show("Running \(job.language) block… (⌘. to cancel)")
1060                session.startBabel(job) { commands.show($0) }
1061            }
1062            guard let path = session.path else { return }
1063            if !job.alwaysAsk, trust.isTrusted(path: path, content: job.blockText) { return run() }
1064            let choices = job.alwaysAsk ? ["yes", "no"] : ["yes", "no", "always"]
1065            commands.ask(Prompt(key: "confirm", message: "Run this \(job.language) block? (\(choices.joined(separator: ", ")))", choices: choices)) { answer in
1066                switch answer {
1067                case "always":
1068                    trust.trust(path: path, content: job.blockText)
1069                    run()
1070                case "yes": run()
1071                default: commands.show("Not run")
1072                }
1073            }
1074        }
1075    }
1076
1077    private struct ReminderKey: Equatable {
1078        var enabled: Bool
1079        var lead: Int
1080        var subfolders: Bool
1081        /// The widgets leave out hidden folders.
1082        var hidden: Set<String>
1083        var files: Int
1084        var changed: Int?
1085        var edits: Int
1086        var hour: Int
1087        /// The widgets' colors.
1088        var theme: ThemeSpec
1089    }
1090
1091    /// Sets the notifications for the next week's timed entries, once edits pause.
1092    private func updateReminders() async {
1093        guard let scheduler else { return }
1094        guard remindersEnabled else {
1095            await scheduler.clear()
1096            return
1097        }
1098        try? await Task.sleep(for: .seconds(2))
1099        guard !Task.isCancelled, !workspace.files.isEmpty else { return }
1100        let agenda = reminderAgenda ?? AgendaModel(workspace: workspace)
1101        reminderAgenda = agenda
1102        agenda.includeSubfolders = agendaSubfolders
1103        agenda.excludeArchives = OrgPreferences.agendaExcludeArchives()
1104        let open = session.openTexts
1105        let reminders = await agenda.reminders(open: open, lead: reminderLead)
1106        guard !Task.isCancelled else { return }
1107        await scheduler.reconcile(reminders)
1108    }
1109
1110    /// The desktop widgets' agenda and habits, written where the widget extension reads them,
1111    /// with the widgets reloaded when they changed.
1112    private func updateWidgets() async {
1113        guard !Task.isCancelled, ProAccess.shared.isUnlocked, !workspace.files.isEmpty, let file = AgendaSnapshot.file() else { return }
1114        let days = widgetAgenda ?? AgendaModel(workspace: workspace)
1115        widgetAgenda = days
1116        days.mode = .agenda(span: AgendaSnapshot.dayCount, startOffset: 0)
1117        days.startOnWeekday = nil
1118        days.includeSubfolders = agendaSubfolders
1119        days.excludeArchives = OrgPreferences.agendaExcludeArchives()
1120        days.hiddenFolders = HiddenFolders.shared.all
1121        days.agendaFiles = OrgPreferences.agendaFiles()
1122        days.options = OrgPreferences.agendaOptions(days.options)
1123        days.options.logMode = false
1124        days.calendarEvents = ProAccess.shared.isUnlocked && OrgPreferences.calendarEvents() && CalendarEvents.isAuthorized ? CalendarAccess.events : nil
1125        days.calendarNames = OrgPreferences.calendarEventCalendars()
1126        days.reminderLists = ProAccess.shared.isUnlocked && OrgPreferences.agendaReminders() && ReminderLists.isAuthorized ? CalendarAccess.reminders : nil
1127        days.reminderListNames = OrgPreferences.agendaReminderLists()
1128        let open = session.openTexts
1129        await days.refresh(open: open)
1130        guard !Task.isCancelled else { return }
1131        if (try? HabitSnapshot(habits: await days.habits(open: open), theme: theme).write()) == true {
1132            WidgetCenter.shared.reloadTimelines(ofKind: "sh.krz.orgstar.habits")
1133        }
1134        let snapshot = AgendaSnapshot(groups: days.groups(), today: days.today, theme: theme, generated: Date())
1135        if (try? snapshot.write(to: file)) == true { WidgetCenter.shared.reloadAllTimelines() }
1136    }
1137
1138    private func loadKeymap() {
1139        let loaded = KeymapLoader.load(preset, commands: Set(EditorCommands.all.map(\.id)))
1140        keymap = loaded.keymap
1141        commands.keymap = loaded.keymap
1142        commands.modal = preset.isModal
1143        if let first = loaded.problems.first {
1144            let more = loaded.problems.count > 1 ? " (and \(loaded.problems.count - 1) more)" : ""
1145            commands.show("keymap.toml: \(first)\(more)")
1146        }
1147    }
1148
1149    /// `SPC b b`: open buffers, most recent first, by name (with the folder when names repeat).
1150    private func switchBuffer() {
1151        let paths = session.recentPaths.dropFirst() + session.recentPaths.prefix(1)
1152        let labels = paths.map(session.bufferName)
1153        guard !labels.isEmpty else { return commands.show("No buffers are open") }
1154        commands.ask(Prompt(key: "buffer", message: "Switch to buffer:", choices: labels)) { answer in
1155            guard let answer, let index = labels.firstIndex(of: answer) else { return }
1156            session.open(Array(paths)[index])
1157        }
1158    }
1159
1160    /// Runs a command from a key, the palette or the Org menu.
1161    private func perform(_ id: String) {
1162        if hiddenCommandIDs.contains(id) {
1163            if let replacement = AppStoreCommands.replacement(for: id) { return perform(replacement) }
1164            return commands.show(Self.unavailable(EditorCommands.all.first { $0.id == id }?.title ?? id))
1165        }
1166        if let feature = ProFeature.required(byCommand: id), !ProAccess.shared.allows(feature) { return }
1167        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.")
1168        if orgOnly, !session.isOrg {
1169            commands.show("Not an org file")
1170            return
1171        }
1172        switch id {
1173        case "app.save":
1174            if !session.save(), session.conflict != nil { commands.showingConflict = true }
1175        case "app.quit": NSApp.terminate(nil)
1176        case "app.save-all":
1177            if !session.saveAll(), session.conflict != nil { commands.showingConflict = true }
1178        case "app.buffer.switch": switchBuffer()
1179        case "app.buffer.next": session.cycle(1)
1180        case "app.buffer.previous": session.cycle(-1)
1181        case "app.buffer.last": session.showPrevious()
1182        case "app.buffer.kill":
1183            if let window = paneWindow, window.paneCount > 1 {
1184                window.closeTab(session.path, in: window.focusedPane, commands: commands)
1185            } else if let path = session.path {
1186                if UnsavedChanges.resolve(session) { session.kill(path) }
1187            } else {
1188                NSApp.keyWindow?.performClose(nil)
1189            }
1190        case "app.buffer.kill-others":
1191            let others = session.openPaths.filter { $0 != session.path }
1192            if UnsavedChanges.resolve(session, paths: others) { others.forEach(session.kill) }
1193        case "app.buffer.kill-all":
1194            let all = session.openPaths
1195            if UnsavedChanges.resolve(session, paths: all) { all.forEach(session.kill) }
1196        case "app.toggle-tab-bar": showTabBar.toggle()
1197        case "app.split-below": paneWindow?.split(.vertical)
1198        case "app.split-right": paneWindow?.split(.horizontal)
1199        case "app.pane-close":
1200            guard let window = paneWindow, window.paneCount > 1 else { return commands.show("Attempt to delete the only pane") }
1201            commands.store.releasePane(window.focused)
1202            window.close(window.focused)
1203            focusPane(window)
1204        case "app.pane-only":
1205            guard let window = paneWindow else { return }
1206            for id in window.layout.panes where id != window.focused { commands.store.releasePane(id) }
1207            window.closeOthers()
1208            focusPane(window)
1209        case "app.pane-next":
1210            guard let window = paneWindow else { return }
1211            window.focusNext()
1212            focusPane(window)
1213        case "app.window-new": openWindow(id: "editor")
1214        case "app.babel.cancel":
1215            if session.isRunningBabel {
1216                session.cancelBabel()
1217            } else if let task = commands.emacsTask {
1218                task.cancel()
1219            } else {
1220                commands.show("Nothing is running")
1221            }
1222        case "app.toggle-outline": toggleOutline()
1223        case "app.toggle-backlinks": backlinksShown.toggle()
1224        case "app.toggle-inspector": inspectorShown.toggle()
1225        case "app.toggle-markup": showMarkup.toggle()
1226        case "app.toggle-line-numbers": showLineNumbers.toggle()
1227        case "app.import-emacs": showingImport = true
1228        case "app.edit-config": commands.jump(path: UserConfig.configFile.path, offset: 0)
1229        case "app.quick-open": commands.showingQuickOpen = true
1230        case "app.palette": commands.showingPalette = true
1231        case "app.search": commands.focusSearch = true
1232        case "app.reload-keymap":
1233            loadKeymap()
1234            commands.show("Keymap reloaded")
1235        case "app.refile", "app.refile.copy":
1236            let keep = id == "app.refile.copy"
1237            let targets = workspace.refileTargets(openPath: session.path, document: session.document)
1238            commands.ask(Prompt(key: "refile", message: keep ? "Copy to:" : "Refile to:", choices: targets.map(\.label))) { answer in
1239                guard let answer else { return }
1240                if let target = targets.first(where: { $0.label == answer }) {
1241                    if let message = session.refile(to: target, keep: keep) { commands.show(message) }
1242                    return
1243                }
1244                // `org-refile-allow-creating-parent-nodes`: `parent/new` adds the heading first.
1245                let creating = OrgPreferences.refileSettings().creating
1246                guard creating != .no, let (parent, child) = RefileSettings.newNode(answer, in: targets) else { return commands.show("Invalid target location") }
1247                let create = {
1248                    switch session.createRefileChild(under: parent, title: child) {
1249                    case .success(let target): if let message = session.refile(to: target, keep: keep) { commands.show(message) }
1250                    case .failure(.message(let message)): commands.show(message)
1251                    }
1252                }
1253                guard creating == .confirm else { return create() }
1254                commands.ask(Prompt(key: "confirm", message: "Create new node \"\(child)\"?", choices: ["yes", "no"])) { reply in
1255                    if reply == "yes" { create() }
1256                }
1257            }
1258        case "app.refile.goto":
1259            // `C-u C-c C-w`: the target heading, or the end of a file.
1260            let targets = workspace.refileTargets(openPath: session.path, document: session.document)
1261            commands.ask(Prompt(key: "refile", message: "Goto:", choices: targets.map(\.label))) { answer in
1262                guard let answer, let target = targets.first(where: { $0.label == answer }) else { return }
1263                commands.jump(path: target.path, offset: target.start ?? Int.max)
1264            }
1265        case "app.archive":
1266            guard reach(session.archiveFile().map { [$0] } ?? []) else { return }
1267            if let message = session.archive() { commands.show(message) }
1268        case "app.table-import":
1269            // `org-table-import`: a TSV, CSV or space-separated file becomes a table at point.
1270            guard let editor = commands.editor else { return commands.show("No file is open") }
1271            let panel = NSOpenPanel()
1272            panel.allowedContentTypes = [.commaSeparatedText, .tabSeparatedText, .plainText]
1273            guard panel.runModal() == .OK, let url = panel.url else { return }
1274            guard let contents = try? String(contentsOf: url, encoding: .utf8) else { return commands.show("Can't read \(url.lastPathComponent)") }
1275            editor.perform(ImportTable(contents: contents))
1276        case "app.table-export":
1277            // `org-table-export`: CSV for a .csv name, else TSV.
1278            guard let editor = commands.editor else { return commands.show("No file is open") }
1279            let context = editor.context()
1280            guard ImportTable.exportText(context.text, at: context.caret, path: "") != nil else { return commands.show("No table at point") }
1281            let panel = NSSavePanel()
1282            panel.nameFieldStringValue = "table.csv"
1283            guard panel.runModal() == .OK, let url = panel.url,
1284                  let text = ImportTable.exportText(context.text, at: context.caret, path: url.path) else { return }
1285            do {
1286                try text.write(to: url, atomically: true, encoding: .utf8)
1287                commands.show("Export done.")
1288            } catch {
1289                commands.show("File not written: \(error.localizedDescription)")
1290            }
1291        case "org.subtree.paste":
1292            guard let text = NSPasteboard.general.string(forType: .string) else { return commands.show("The clipboard is empty") }
1293            commands.editor?.perform(PasteSubtree(text: text))
1294        case "org.link.insert":
1295            commands.editor?.perform(InsertLink(stored: commands.storedLinks, file: session.path))
1296        case "org.link.store":
1297            guard let editor = commands.editor, let path = session.path else { return commands.show("No method for storing a link from this buffer") }
1298            let context = editor.context()
1299            let denote = OrgPreferences.usesDenote() ? Links.storeDenote(in: context, path: path) : nil
1300            commands.storeLink(denote ?? Links.store(in: context, path: Links.abbreviate(path, home: OrgPaths.home)))
1301        case "org.id.store-link":
1302            guard let editor = commands.editor, let path = session.path else { return }
1303            if case .commit = editor.perform(CreateID()),
1304               let link = Links.storeID(in: editor.context(), fileName: (path as NSString).lastPathComponent) {
1305                commands.storeLink(link)
1306            }
1307        case "app.agenda":
1308            openWindow(id: "agenda")
1309        case "app.clock.in":
1310            clockIn(.caret)
1311        case "app.clock.in-recent":
1312            clockIn(.select)
1313        case "app.clock.in-last":
1314            clockIn(.last)
1315        case let id where id.hasPrefix("app.clock.history."):
1316            if let index = Int(id.dropFirst("app.clock.history.".count)), index < clock.history.count { clockIn(.task(clock.history[index])) }
1317        case "app.clock.out":
1318            commands.show(clock.clockOut(session))
1319        case "app.clock.cancel":
1320            commands.show(clock.clockOut(session, cancel: true))
1321        case "app.clock.goto":
1322            let found = clock.goto(session)
1323            if let location = found.location { commands.jump(path: location.path, offset: location.offset) }
1324            if let message = found.message { commands.show(message) }
1325        case "app.clock.goto-recent":
1326            Task {
1327                let found = await clock.gotoRecent(session, ask: askClock)
1328                if let location = found.location { commands.jump(path: location.path, offset: location.offset) }
1329                if let message = found.message { commands.show(message) }
1330            }
1331        case "app.clock.default":
1332            commands.show(clock.markDefault(session))
1333        case "app.clock.resolve":
1334            Task { report(await clock.resolveOpenClocks(session, paths: orgFiles, ask: askClock)) }
1335        case "app.clock.report":
1336            openWindow(id: "clock-report")
1337        case "app.board":
1338            openWindow(id: "board")
1339        case "app.capture":
1340            NSApp.activate()
1341            openWindow(id: "capture")
1342        case "app.revert":
1343            // `:e`: the file as it is on disk; unsaved changes go to recovery.
1344            guard session.path != nil else { return commands.show("No file is open") }
1345            session.useDiskVersion()
1346            commands.show("Reverted to the file on disk")
1347        case "app.sync-conflicts":
1348            guard session.path != nil else { return commands.show("No file is open") }
1349            panel = .syncCopies(UUID())
1350        case "app.recovery":
1351            guard session.path != nil else { return commands.show("No file is open") }
1352            panel = .recovery(UUID())
1353        case "app.copy-rich-text":
1354            copyRichText()
1355        case "app.export-dialog":
1356            guard let path = session.path else { return commands.show("No file is open") }
1357            panel = .export(UUID(), URL(fileURLWithPath: path))
1358        case let id where id.hasPrefix("app.export."):
1359            export(String(id.dropFirst("app.export.".count)))
1360        case let id where id.hasPrefix("app.publish"):
1361            publish(id)
1362        case "app.plot":
1363            plotTable()
1364        case let id where id.hasPrefix("app.crypt."):
1365            crypt(id)
1366        case let id where id.hasPrefix("app.attach."):
1367            guard reach(attachActions.entry().flatMap { Attachments.directory($0, noFSCheck: true) }.map { [$0] } ?? [], directories: true) else { return }
1368            attachActions.run(id)
1369        case let id where id.hasPrefix("app.dailies.") || id.hasPrefix("app.node."):
1370            roamActions.run(id)
1371        default:
1372            if let editor = commands.editor { editor.run(id) } else { commands.show("No file is open") }
1373        }
1374    }
1375
1376    private var askClock: ClockModel.Ask { commands.askClock }
1377
1378    /// The files `org-resolve-clocks` looks through: the workspace's org files.
1379    private var orgFiles: [String] { workspace.files.filter { $0.kind == .org }.map(\.path) }
1380
1381    private func clockIn(_ target: ClockModel.Target) {
1382        Task { report(await clock.clockIn(session, target: target, paths: orgFiles, ask: askClock)) }
1383    }
1384
1385    /// The last message of a clock command, and the clock to show for `j`.
1386    private func report(_ outcome: ClockModel.Outcome) {
1387        if let jump = outcome.jump { commands.jump(path: jump.path, offset: jump.offset) }
1388        if let message = outcome.messages.last(where: { !$0.isEmpty }) { commands.show(message) }
1389    }
1390
1391    private var errorShown: Binding<Bool> {
1392        Binding(get: { workspace.lastError != nil || session.lastError != nil }, set: { _ in })
1393    }
1394}
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