Sources/Orgstar/ContentView.swift

28d8fe3d2501e91a1294d65c28e5deceb36a5930
orgstar/Sources/Orgstar/ContentView.swift

933 lines · 49973 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) { offset in commands.editor?.reveal(offset) }
334            case .export(_, let source):
335                ExportSheet(source: source, inSubtree: exportSubtreeAvailable, target: exportTarget) { format, destination, open, subtree, bodyOnly in
336                    export(format, to: destination, open: open, subtree: subtree, bodyOnly: bodyOnly)
337                }
338            case .conflict:
339                ConflictSheet(session: session)
340            case .syncCopies:
341                SyncConflictSheet(session: session) { commands.show($0) }
342            case .recovery:
343                RecoverySheet(session: session) { commands.show($0) }
344            }
345        }
346        .sheet(item: $blockEdit) { request in
347            BlockEditorView(edit: request.edit) { content in
348                blockEdit = nil
349                guard let content else { return }
350                commands.editor?.perform(ReplaceBlockLines(edit: request.edit, content: content))
351            }
352        }
353        .sheet(isPresented: $commands.showingPalette) {
354            PaletteView(commands: commands) { id in
355                commands.showingPalette = false
356                // After the sheet closes, so app commands can present their own, and in the
357                // pane that had the focus when it opened: closing a sheet makes this window key.
358                DispatchQueue.main.async {
359                    restoreSheetTarget()
360                    perform(id)
361                }
362            }
363        }
364        .onChange(of: commands.showingPalette) { _, showing in if showing { sheetTarget = session.focused } }
365        .onChange(of: commands.showingQuickOpen) { _, showing in if showing { sheetTarget = session.focused } }
366        .onChange(of: session.conflict) { _, conflict in
367            if conflict != nil { commands.showingConflict = true }
368        }
369        .onChange(of: commands.showingConflict) { _, showing in
370            guard showing else { return }
371            commands.showingConflict = false
372            if session.conflict != nil { panel = .conflict(UUID()) }
373        }
374        .onChange(of: workspace.changedFile?.version) {
375            if let path = workspace.changedFile?.path { session.fileChanged(path) }
376        }
377    }
378
379    var body: some View {
380        main
381        .onChange(of: ClockMenuState(running: clock.running, history: clock.history), initial: true) { _, state in
382            if statusItem == nil { statusItem = ClockStatusItem { commands.run($0) } }
383            statusItem?.update(state.running, recent: state.history.map(\.title))
384        }
385        .onChange(of: globalCapture, initial: true) { _, enabled in
386            hotKey?.unregister()
387            hotKey = enabled ? GlobalHotKey { perform("app.capture") } : nil
388        }
389        .onChange(of: commands.runRequest?.serial, initial: true) {
390            if let id = commands.runRequest?.id { perform(id) }
391        }
392        .onChange(of: ConfigSync.shared.problems, initial: true) { _, problems in
393            if let first = problems.first {
394                commands.show(first + (problems.count > 1 ? " (and \(problems.count - 1) more)" : ""))
395            }
396        }
397        .onChange(of: ConfigSync.shared.changedFile?.serial) {
398            if ConfigSync.shared.changedFile?.name == "keymap.toml" { loadKeymap() }
399        }
400        .onChange(of: commands.jumpRequest?.id) {
401            guard let request = commands.jumpRequest else { return }
402            if request.path != session.path {
403                session.open(request.path)
404                selectedFile = request.path
405            }
406            session.reveal(request.offset)
407        }
408        .onChange(of: commands.focusSearch) { _, focus in
409            if focus {
410                searchFocused = true
411                commands.focusSearch = false
412            }
413        }
414        .fileImporter(isPresented: $commands.showingFolderPicker, allowedContentTypes: [.folder]) { result in
415            guard case .success(let url) = result else { return }
416            Task {
417                do { try await workspace.addRoot(url) } catch { workspace.lastError = error.localizedDescription }
418            }
419        }
420        .sheet(isPresented: $commands.showingQuickOpen) {
421            QuickOpenView(workspace: workspace) { entry in
422                commands.showingQuickOpen = false
423                DispatchQueue.main.async {
424                    restoreSheetTarget()
425                    selectedFile = entry.path
426                    if selectedFile == entry.path { session.open(entry.path) }
427                }
428            }
429        }
430        .alert("orgstar", isPresented: errorShown) {
431            Button("OK") {
432                workspace.lastError = nil
433                session.lastError = nil
434            }
435        } message: {
436            Text(workspace.lastError ?? session.lastError ?? "")
437        }
438        .task(id: ReminderKey(
439            enabled: remindersEnabled, lead: reminderLead, subfolders: agendaSubfolders, files: workspace.files.count,
440            changed: workspace.changedFile?.version, edits: session.editVersion, hour: hour
441        )) {
442            await updateReminders()
443        }
444        .task {
445            while !Task.isCancelled {
446                try? await Task.sleep(for: .seconds(3600))
447                hour += 1
448            }
449        }
450        // `org-resolve-clocks-if-idle`, checked every minute while a clock runs.
451        .task(id: "\(clock.running?.start ?? "") \(clockIdleTime)") {
452            guard clock.running != nil, clockIdleTime > 0 else { return }
453            while !Task.isCancelled {
454                try? await Task.sleep(for: .seconds(60))
455                guard !Task.isCancelled, clock.running != nil, !clock.isResolving else { continue }
456                let idle = ClockIdle.seconds()
457                guard idle > Double(clockIdleTime * 60) else { continue }
458                NSApp.requestUserAttention(.informationalRequest)
459                report(await clock.resolveIdle(session, idleSince: Date().addingTimeInterval(-idle), ask: askClock))
460            }
461        }
462        .task {
463            DevelopmentHooks.scheduleSnapshot()
464            pendingCarets = BufferRestore.restore(session)
465            if let path = session.path, let caret = pendingCarets.removeValue(forKey: path) { session.reveal(caret) }
466            // Files handed over at launch open after the restored buffers, and show.
467            for path in AppDelegate.pendingOpens { session.open(path) }
468            AppDelegate.pendingOpens = []
469            for link in AppDelegate.pendingLinks + [DevelopmentHooks.urlToOpen].compactMap({ $0 }) { commands.handle(protocolURL: link) }
470            AppDelegate.pendingLinks = []
471            if let path = DevelopmentHooks.fileToOpen { selectedFile = path }
472            if let root = DevelopmentHooks.rootToAdd { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
473            if let commandList = DevelopmentHooks.commandToRun {
474                // The file opened above needs its editor first.
475                for _ in 0..<20 where DevelopmentHooks.fileToOpen != nil && commands.editor == nil { try? await Task.sleep(for: .milliseconds(100)) }
476                for command in commandList.split(separator: ",") { perform(String(command)) }
477                for answer in DevelopmentHooks.answers {
478                    for _ in 0..<20 where commands.prompt == nil { try? await Task.sleep(for: .milliseconds(100)) }
479                    commands.answer(answer)
480                }
481            }
482            if let id = DevelopmentHooks.windowToOpen {
483                if id == "settings" { openSettings() } else { openWindow(id: id) }
484            }
485            await workspace.refresh()
486            workspace.startWatching()
487        }
488    }
489
490    /// The selection, or the whole file without one, on the clipboard as HTML, RTF and plain
491    /// text, to paste formatted into mail and documents.
492    private func copyRichText() {
493        guard let path = session.path, let whole = session.document?.text, let editor = commands.editor else { return commands.show("No file is open") }
494        let defaults = Preferences.orgSettings.resolvingSetupFiles(in: whole, path: path, read: OrgSettings.readFile)
495        let selection = editor.context().selection.first { !$0.isEmpty }
496        let selected = selection.map { (whole as NSString).substring(with: NSRange($0)) }
497        let url = URL(fileURLWithPath: path)
498        let html = HTMLExport.page(
499            selected ?? whole, fallbackTitle: url.deletingPathExtension().lastPathComponent, settings: defaults, path: path, bodyOnly: selected != nil,
500            codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme)
501        )
502        do {
503            try RichTextExport.copy(html: html, directory: url.deletingLastPathComponent())
504            commands.show(selected == nil ? "Copied the file as rich text" : "Copied the selection as rich text")
505        } catch {
506            commands.show("\(error)")
507        }
508    }
509
510    /// Whether the caret is in a heading's subtree, which the export dialog can export alone.
511    private var exportSubtreeAvailable: Bool {
512        guard let text = session.document?.text, let caret = commands.editor?.context().caret else { return false }
513        return ExportScope.subtree(text, at: caret) != nil
514    }
515
516    /// Where an export goes by default: `#+EXPORT_FILE_NAME`, or the subtree's
517    /// `EXPORT_FILE_NAME`, else beside the file, with `ext`.
518    private func exportTarget(_ ext: String, subtree: Bool) -> URL {
519        let path = session.path ?? ""
520        let text = session.document?.text ?? ""
521        let caret = subtree ? commands.editor?.context().caret : nil
522        return ExportScope.output(for: URL(fileURLWithPath: path), name: ExportScope.fileName(text, subtreeAt: caret), extension: ext)
523    }
524
525    /// Writes the export where `#+EXPORT_FILE_NAME` says or beside the file, as Emacs's export
526    /// dispatcher does, or to `destination`, and opens it with `open`. `subtree` exports the
527    /// subtree at the caret alone; `bodyOnly` leaves out the title and page wrapper.
528    private func export(_ format: String, to destination: URL? = nil, open: Bool = false, subtree: Bool = false, bodyOnly: Bool = false) {
529        guard let path = session.path, var text = session.document?.text else {
530            commands.show("No file is open")
531            return
532        }
533        let url = URL(fileURLWithPath: path)
534        let base = url.deletingPathExtension()
535        let defaults = Preferences.orgSettings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
536        let open = open || format == "html-open"
537        let caret = commands.editor?.context().caret ?? 0
538        let whole = text
539        if subtree {
540            guard let narrowed = ExportScope.subtree(text, at: caret, settings: defaults) else { return commands.show("Not in a subtree") }
541            text = narrowed
542        }
543        switch format {
544        case "html", "html-open", "markdown":
545            let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
546            let target = destination ?? ExportScope.output(for: url, name: name, extension: format == "markdown" ? "md" : "html")
547            let content = format == "markdown"
548                ? MarkdownExport.document(text, settings: defaults, path: path, bodyOnly: bodyOnly)
549                : HTMLExport.page(
550                    text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path, bodyOnly: bodyOnly,
551                    codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme)
552                )
553            do {
554                try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
555                try content.write(to: target, atomically: true, encoding: .utf8)
556                commands.show("Exported to \(target.lastPathComponent)")
557                if open { NSWorkspace.shared.open(target) }
558            } catch {
559                commands.show("Can't write \(target.lastPathComponent): \(error.localizedDescription)")
560            }
561        case "print-pdf", "docx", "rtf", "plain-text":
562            let ext = ["print-pdf": "pdf", "plain-text": "txt"][format] ?? format
563            let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
564            let target = destination ?? ExportScope.output(for: url, name: name, extension: ext)
565            let html = HTMLExport.page(
566                text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path,
567                codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme)
568            )
569            let directory = url.deletingLastPathComponent()
570            if format == "print-pdf" { commands.show("Exporting to PDF…") }
571            Task {
572                do {
573                    let data: Data
574                    switch format {
575                    case "print-pdf": data = try await PDFExport.pdf(html: html, directory: directory)
576                    case "docx": data = try RichTextExport.docx(RichTextExport.attributed(html: html, directory: directory))
577                    case "rtf": data = try RichTextExport.rtf(RichTextExport.attributed(html: html, directory: directory))
578                    default: data = Data(RichTextExport.plain(try RichTextExport.attributed(html: html, directory: directory)).utf8)
579                    }
580                    try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
581                    try data.write(to: target, options: .atomic)
582                    commands.show("Exported to \(target.lastPathComponent)")
583                    if open { NSWorkspace.shared.open(target) }
584                } catch {
585                    commands.show("Can't export \(target.lastPathComponent): \(error)")
586                }
587            }
588        default:
589            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"]
590            guard let function = functions[format] else { return }
591            commands.show("Exporting with Emacs…")
592            commands.runInEmacs {
593                do {
594                    // Emacs narrows to the subtree and reads EXPORT_FILE_NAME itself.
595                    let point = subtree ? (whole as NSString).substring(to: min(caret, (whole as NSString).length)).unicodeScalars.count + 1 : nil
596                    var written = URL(fileURLWithPath: try await EmacsRunner.export(
597                        text: whole, path: path, function: function, subtree: point, bodyOnly: bodyOnly
598                    ))
599                    if let destination, destination.standardizedFileURL != written.standardizedFileURL {
600                        try? FileManager.default.removeItem(at: destination)
601                        try FileManager.default.moveItem(at: written, to: destination)
602                        written = destination
603                    }
604                    commands.show("Exported to \(written.lastPathComponent)")
605                    if open { NSWorkspace.shared.open(written) }
606                } catch is CancellationError {
607                    commands.show("Export canceled")
608                } catch {
609                    commands.show("\(error)")
610                }
611            }
612        }
613    }
614
615    /// Work a command hands to the platform: tables recalculated in Emacs.
616    private func runExternal(_ request: ExternalRequest) {
617        switch request {
618        case .openLink(let link):
619            if let message = LinkOpener.open(link, session: session, workspace: workspace) { commands.show(message) }
620            // `org-occur` for a regexp link, once the editor shows the file.
621            if let regexp = Links.regexpSearch(link) {
622                DispatchQueue.main.async { commands.editor?.perform(SparseTreeCommand(), answers: ["sparse": "/", "regexp": regexp]) }
623            }
624        case .tangle(let scope):
625            commands.show(session.tangle(scope))
626        case .agenda(let start, let days):
627            commands.agendaRequest = (start, days)
628            openWindow(id: "agenda")
629        case .editBlock(let edit):
630            blockEdit = BlockEditRequest(edit: edit)
631        case .columnView(let view):
632            panel = .columns(UUID(), view)
633        case .emacsTable(let table, let point, let form, let reason, let lisp):
634            let run = {
635                commands.show("Recalculating in Emacs (\(reason))…")
636                commands.runInEmacs { commands.show(await session.recalculateInEmacs(table: table, point: point, form: form)) }
637            }
638            guard lisp, let path = session.path, let text = session.document?.text else { return run() }
639            let content = (text as NSString).substring(with: NSRange(location: table.lowerBound, length: min((text as NSString).length, table.upperBound + 2000) - table.lowerBound))
640            if trust.isTrusted(path: path, content: content) { return run() }
641            commands.ask(Prompt(key: "confirm", message: "This table's formulas run Lisp. Run them? (yes, no, always)", choices: ["yes", "no", "always"])) { answer in
642                switch answer {
643                case "always":
644                    trust.trust(path: path, content: content)
645                    run()
646                case "yes": run()
647                default: commands.show("Not recalculated")
648                }
649            }
650        case .babel(let job):
651            let run = {
652                commands.show("Running \(job.language) block… (⌘. to cancel)")
653                session.startBabel(job) { commands.show($0) }
654            }
655            guard let path = session.path else { return }
656            if !job.alwaysAsk, trust.isTrusted(path: path, content: job.blockText) { return run() }
657            let choices = job.alwaysAsk ? ["yes", "no"] : ["yes", "no", "always"]
658            commands.ask(Prompt(key: "confirm", message: "Run this \(job.language) block? (\(choices.joined(separator: ", ")))", choices: choices)) { answer in
659                switch answer {
660                case "always":
661                    trust.trust(path: path, content: job.blockText)
662                    run()
663                case "yes": run()
664                default: commands.show("Not run")
665                }
666            }
667        }
668    }
669
670    private struct ReminderKey: Hashable {
671        var enabled: Bool
672        var lead: Int
673        var subfolders: Bool
674        var files: Int
675        var changed: Int?
676        var edits: Int
677        var hour: Int
678    }
679
680    /// Sets the notifications for the next week's timed entries, once edits pause.
681    private func updateReminders() async {
682        guard let scheduler else { return }
683        guard remindersEnabled else {
684            await scheduler.clear()
685            return
686        }
687        try? await Task.sleep(for: .seconds(2))
688        guard !Task.isCancelled, !workspace.files.isEmpty else { return }
689        let agenda = reminderAgenda ?? AgendaModel(workspace: workspace)
690        reminderAgenda = agenda
691        agenda.includeSubfolders = agendaSubfolders
692        let open = session.openTexts
693        let reminders = await agenda.reminders(open: open, lead: reminderLead)
694        guard !Task.isCancelled else { return }
695        await scheduler.reconcile(reminders)
696    }
697
698    private func loadKeymap() {
699        let loaded = KeymapLoader.load(preset, commands: Set(EditorCommands.all.map(\.id)))
700        keymap = loaded.keymap
701        commands.keymap = loaded.keymap
702        commands.modal = preset.isModal
703        if let first = loaded.problems.first {
704            let more = loaded.problems.count > 1 ? " (and \(loaded.problems.count - 1) more)" : ""
705            commands.show("keymap.toml: \(first)\(more)")
706        }
707    }
708
709    /// `SPC b b`: open buffers, most recent first, by name (with the folder when names repeat).
710    private func switchBuffer() {
711        let paths = session.recentPaths.dropFirst() + session.recentPaths.prefix(1)
712        let labels = paths.map(session.bufferName)
713        guard !labels.isEmpty else { return commands.show("No buffers are open") }
714        commands.ask(Prompt(key: "buffer", message: "Switch to buffer:", choices: labels)) { answer in
715            guard let answer, let index = labels.firstIndex(of: answer) else { return }
716            session.open(Array(paths)[index])
717        }
718    }
719
720    /// Runs a command from a key, the palette or the Org menu.
721    private func perform(_ id: String) {
722        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("org.")
723        if orgOnly, !session.isOrg {
724            commands.show("Not an org file")
725            return
726        }
727        switch id {
728        case "app.save":
729            if !session.save(), session.conflict != nil { commands.showingConflict = true }
730        case "app.quit": NSApp.terminate(nil)
731        case "app.save-all":
732            if !session.saveAll(), session.conflict != nil { commands.showingConflict = true }
733        case "app.buffer.switch": switchBuffer()
734        case "app.buffer.next": session.cycle(1)
735        case "app.buffer.previous": session.cycle(-1)
736        case "app.buffer.last": session.showPrevious()
737        case "app.buffer.kill":
738            guard let path = session.path else {
739                NSApp.keyWindow?.performClose(nil)
740                return
741            }
742            if UnsavedChanges.resolve(session) { session.kill(path) }
743        case "app.buffer.kill-others":
744            let others = session.openPaths.filter { $0 != session.path }
745            if UnsavedChanges.resolve(session, paths: others) { others.forEach(session.kill) }
746        case "app.buffer.kill-all":
747            let all = session.openPaths
748            if UnsavedChanges.resolve(session, paths: all) { all.forEach(session.kill) }
749        case "app.toggle-tab-bar": showTabBar.toggle()
750        case "app.split-below": paneWindow?.split(.vertical)
751        case "app.split-right": paneWindow?.split(.horizontal)
752        case "app.pane-close":
753            guard let window = paneWindow, window.paneCount > 1 else { return commands.show("Attempt to delete the only pane") }
754            commands.store.releasePane(window.focused)
755            window.close(window.focused)
756            focusPane(window)
757        case "app.pane-only":
758            guard let window = paneWindow else { return }
759            for id in window.layout.panes where id != window.focused { commands.store.releasePane(id) }
760            window.closeOthers()
761            focusPane(window)
762        case "app.pane-next":
763            guard let window = paneWindow else { return }
764            window.focusNext()
765            focusPane(window)
766        case "app.window-new": openWindow(id: "editor")
767        case "app.babel.cancel":
768            if session.isRunningBabel {
769                session.cancelBabel()
770            } else if let task = commands.emacsTask {
771                task.cancel()
772            } else {
773                commands.show("Nothing is running")
774            }
775        case "app.toggle-outline": toggleOutline()
776        case "app.toggle-backlinks": backlinksShown.toggle()
777        case "app.toggle-inspector": inspectorShown.toggle()
778        case "app.toggle-markup": showMarkup.toggle()
779        case "app.toggle-line-numbers": showLineNumbers.toggle()
780        case "app.import-emacs": showingImport = true
781        case "app.edit-config": commands.jump(path: UserConfig.configFile.path, offset: 0)
782        case "app.quick-open": commands.showingQuickOpen = true
783        case "app.palette": commands.showingPalette = true
784        case "app.search": commands.focusSearch = true
785        case "app.reload-keymap":
786            loadKeymap()
787            commands.show("Keymap reloaded")
788        case "app.refile", "app.refile.copy":
789            let keep = id == "app.refile.copy"
790            let targets = workspace.refileTargets(openPath: session.path, document: session.document)
791            commands.ask(Prompt(key: "refile", message: keep ? "Copy to:" : "Refile to:", choices: targets.map(\.label))) { answer in
792                guard let answer else { return }
793                if let target = targets.first(where: { $0.label == answer }) {
794                    if let message = session.refile(to: target, keep: keep) { commands.show(message) }
795                    return
796                }
797                // `org-refile-allow-creating-parent-nodes`: `parent/new` adds the heading first.
798                let creating = OrgPreferences.refileSettings().creating
799                guard creating != .no, let (parent, child) = RefileSettings.newNode(answer, in: targets) else { return commands.show("Invalid target location") }
800                let create = {
801                    switch session.createRefileChild(under: parent, title: child) {
802                    case .success(let target): if let message = session.refile(to: target, keep: keep) { commands.show(message) }
803                    case .failure(.message(let message)): commands.show(message)
804                    }
805                }
806                guard creating == .confirm else { return create() }
807                commands.ask(Prompt(key: "confirm", message: "Create new node \"\(child)\"?", choices: ["yes", "no"])) { reply in
808                    if reply == "yes" { create() }
809                }
810            }
811        case "app.refile.goto":
812            // `C-u C-c C-w`: the target heading, or the end of a file.
813            let targets = workspace.refileTargets(openPath: session.path, document: session.document)
814            commands.ask(Prompt(key: "refile", message: "Goto:", choices: targets.map(\.label))) { answer in
815                guard let answer, let target = targets.first(where: { $0.label == answer }) else { return }
816                commands.jump(path: target.path, offset: target.start ?? Int.max)
817            }
818        case "app.archive":
819            if let message = session.archive() { commands.show(message) }
820        case "app.table-import":
821            // `org-table-import`: a TSV, CSV or space-separated file becomes a table at point.
822            guard let editor = commands.editor else { return commands.show("No file is open") }
823            let panel = NSOpenPanel()
824            panel.allowedContentTypes = [.commaSeparatedText, .tabSeparatedText, .plainText]
825            guard panel.runModal() == .OK, let url = panel.url else { return }
826            guard let contents = try? String(contentsOf: url, encoding: .utf8) else { return commands.show("Can't read \(url.lastPathComponent)") }
827            editor.perform(ImportTable(contents: contents))
828        case "app.table-export":
829            // `org-table-export`: CSV for a .csv name, else TSV.
830            guard let editor = commands.editor else { return commands.show("No file is open") }
831            let context = editor.context()
832            guard ImportTable.exportText(context.text, at: context.caret, path: "") != nil else { return commands.show("No table at point") }
833            let panel = NSSavePanel()
834            panel.nameFieldStringValue = "table.csv"
835            guard panel.runModal() == .OK, let url = panel.url,
836                  let text = ImportTable.exportText(context.text, at: context.caret, path: url.path) else { return }
837            do {
838                try text.write(to: url, atomically: true, encoding: .utf8)
839                commands.show("Export done.")
840            } catch {
841                commands.show("File not written: \(error.localizedDescription)")
842            }
843        case "org.subtree.paste":
844            guard let text = NSPasteboard.general.string(forType: .string) else { return commands.show("The clipboard is empty") }
845            commands.editor?.perform(PasteSubtree(text: text))
846        case "org.link.insert":
847            commands.editor?.perform(InsertLink(stored: commands.storedLinks, file: session.path))
848        case "org.link.store":
849            guard let editor = commands.editor, let path = session.path else { return commands.show("No method for storing a link from this buffer") }
850            commands.storeLink(Links.store(in: editor.context(), path: Links.abbreviate(path, home: NSHomeDirectory())))
851        case "org.id.store-link":
852            guard let editor = commands.editor, let path = session.path else { return }
853            if case .commit = editor.perform(CreateID()),
854               let link = Links.storeID(in: editor.context(), fileName: (path as NSString).lastPathComponent) {
855                commands.storeLink(link)
856            }
857        case "app.agenda":
858            openWindow(id: "agenda")
859        case "app.clock.in":
860            clockIn(.caret)
861        case "app.clock.in-recent":
862            clockIn(.select)
863        case "app.clock.in-last":
864            clockIn(.last)
865        case let id where id.hasPrefix("app.clock.history."):
866            if let index = Int(id.dropFirst("app.clock.history.".count)), index < clock.history.count { clockIn(.task(clock.history[index])) }
867        case "app.clock.out":
868            commands.show(clock.clockOut(session))
869        case "app.clock.cancel":
870            commands.show(clock.clockOut(session, cancel: true))
871        case "app.clock.goto":
872            let found = clock.goto(session)
873            if let location = found.location { commands.jump(path: location.path, offset: location.offset) }
874            if let message = found.message { commands.show(message) }
875        case "app.clock.goto-recent":
876            Task {
877                let found = await clock.gotoRecent(session, ask: askClock)
878                if let location = found.location { commands.jump(path: location.path, offset: location.offset) }
879                if let message = found.message { commands.show(message) }
880            }
881        case "app.clock.default":
882            commands.show(clock.markDefault(session))
883        case "app.clock.resolve":
884            Task { report(await clock.resolveOpenClocks(session, paths: orgFiles, ask: askClock)) }
885        case "app.clock.report":
886            openWindow(id: "clock-report")
887        case "app.board":
888            openWindow(id: "board")
889        case "app.capture":
890            NSApp.activate()
891            openWindow(id: "capture")
892        case "app.revert":
893            // `:e`: the file as it is on disk; unsaved changes go to recovery.
894            guard session.path != nil else { return commands.show("No file is open") }
895            session.useDiskVersion()
896            commands.show("Reverted to the file on disk")
897        case "app.sync-conflicts":
898            guard session.path != nil else { return commands.show("No file is open") }
899            panel = .syncCopies(UUID())
900        case "app.recovery":
901            guard session.path != nil else { return commands.show("No file is open") }
902            panel = .recovery(UUID())
903        case "app.copy-rich-text":
904            copyRichText()
905        case "app.export-dialog":
906            guard let path = session.path else { return commands.show("No file is open") }
907            panel = .export(UUID(), URL(fileURLWithPath: path))
908        case let id where id.hasPrefix("app.export."):
909            export(String(id.dropFirst("app.export.".count)))
910        default:
911            if let editor = commands.editor { editor.run(id) } else { commands.show("No file is open") }
912        }
913    }
914
915    private var askClock: ClockModel.Ask { commands.askClock }
916
917    /// The files `org-resolve-clocks` looks through: the workspace's org files.
918    private var orgFiles: [String] { workspace.files.filter { $0.kind == .org }.map(\.path) }
919
920    private func clockIn(_ target: ClockModel.Target) {
921        Task { report(await clock.clockIn(session, target: target, paths: orgFiles, ask: askClock)) }
922    }
923
924    /// The last message of a clock command, and the clock to show for `j`.
925    private func report(_ outcome: ClockModel.Outcome) {
926        if let jump = outcome.jump { commands.jump(path: jump.path, offset: jump.offset) }
927        if let message = outcome.messages.last(where: { !$0.isEmpty }) { commands.show(message) }
928    }
929
930    private var errorShown: Binding<Bool> {
931        Binding(get: { workspace.lastError != nil || session.lastError != nil }, set: { _ in })
932    }
933}
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