Sources/Orgstar/ContentView.swift

d5a3274dbc5b547e5824fe6aca87b7b26cbc9b4a
orgstar/Sources/Orgstar/ContentView.swift

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