Sources/Orgstar/ContentView.swift

bff4593da6ab846d70075a6a8bbbbc97ec5634f1
orgstar/Sources/Orgstar/ContentView.swift

1236 lines · 67804 bytes

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