Sources/Orgstar/ContentView.swift

213799f3f0792831bdbd707d1f85cb19b614f39f
orgstar/Sources/Orgstar/ContentView.swift

1288 lines · 70752 bytes

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