Sources/Orgstar/ContentView.swift

0e0e407283348bd34049ed9fd407e459e98d4d07
orgstar/Sources/Orgstar/ContentView.swift

1165 lines · 63340 bytes

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