Sources/Orgstar/ContentView.swift

6236c2f7de7b4f3c92176353e4a33e66b9181766
orgstar/Sources/Orgstar/ContentView.swift

1205 lines · 66030 bytes

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