Sources/Orgstar/ContentView.swift

fe955aa1d55ae76aca91363db3f7ba8e18fe90b6
orgstar/Sources/Orgstar/ContentView.swift

796 lines · 42552 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    private var options: EditingOptions {
 56        Preferences.options(
 57            tagsColumn: tagsColumn, headingAfterSubtree: headingAfterSubtree, splitLine: splitLine, alphabeticalLists: alphabeticalLists,
 58            fillColumn: fillColumn, hiddenMarkers: hiddenMarkers, prettyEntities: prettyEntities, logDone: logDone, logIntoDrawer: logIntoDrawer,
 59            hideDrawerStartup: hideDrawerStartup, hideBlockStartup: hideBlockStartup, logReschedule: logReschedule, logRedeadline: logRedeadline,
 60            useSpeedCommands: useSpeedCommands, startupWithInlineImages: startupWithInlineImages,
 61            startupIndented: startupIndented, hideLeadingStars: hideLeadingStars, startupAlignAllTables: startupAlignAllTables,
 62            startupTruncated: startupTruncated, spellCheck: spellCheck, electricPair: electricPair,
 63            enforceTodoDependencies: enforceTodoDependencies, enforceTodoCheckboxDependencies: enforceTodoCheckboxDependencies
 64        )
 65    }
 66    /// A block being edited apart (`org-edit-special`).
 67    @State private var blockEdit: BlockEditRequest?
 68    /// A sheet a command opened: column view or the export dialog.
 69    @State private var panel: Panel?
 70
 71    @State private var selectedFile: String?
 72    /// A file that isn't text, shown as a preview instead of the open document.
 73    @State private var previewPath: String?
 74    @AppStorage("outlineShown") private var orgOutlineShown = true
 75    @AppStorage("outlineWidth") private var outlineWidth = 220.0
 76    @AppStorage("backlinksShown") private var backlinksShown = true
 77    @AppStorage("inspectorShown") private var inspectorShown = false
 78    @AppStorage("showMarkup") private var showMarkup = false
 79    @AppStorage("showLineNumbers") private var showLineNumbers = true
 80    @AppStorage("showHiddenFiles") private var showHiddenFiles = true
 81    @AppStorage("ignoredFolders") private var ignoredFolders = ScanRules.defaultIgnoredFolders.sorted().joined(separator: " ")
 82    @AppStorage("themeFont") private var themeFont = ""
 83    @AppStorage("themeFontSize") private var themeFontSize = 13
 84    @AppStorage("themeLineSpacing") private var themeLineSpacing = 2
 85    @AppStorage("themeHeadingStep") private var themeHeadingStep = 1
 86
 87    /// The theme's colors from config.toml with the type settings.
 88    private var theme: ThemeSpec {
 89        var spec = ConfigSync.shared.theme
 90        spec.font = themeFont
 91        spec.fontSize = themeFontSize
 92        spec.lineSpacing = themeLineSpacing
 93        spec.headingSizeStep = themeHeadingStep
 94        return spec
 95    }
 96    /// The outline for a file that isn't org, off until asked for.
 97    @State private var plainOutlineShown = false
 98    @State private var showingImport = false
 99    @AppStorage("showTabBar") private var showTabBar = false
100    /// Carets of restored buffers, shown when each first shows.
101    @State private var pendingCarets: [String: Int] = [:]
102    @State private var query = ""
103    @FocusState private var searchFocused: Bool
104    @Environment(\.openWindow) private var openWindow
105    @Environment(\.openSettings) private var openSettings
106
107    /// Whether the outline pane shows: remembered for org files, hidden by default for
108    /// other files, and always shown while search results are up.
109    private var outlineShown: Bool {
110        !query.isEmpty || (previewPath == nil && (session.isOrg ? orgOutlineShown : plainOutlineShown))
111    }
112
113    private func toggleOutline() {
114        if session.isOrg { orgOutlineShown.toggle() } else { plainOutlineShown.toggle() }
115    }
116
117    @ViewBuilder
118    private var detail: some View {
119        if let previewPath {
120            FilePreview(path: previewPath)
121        } else if session.path != nil {
122            VStack(spacing: 0) {
123                if showTabBar { BufferTabs(session: session) }
124                EditorView(session: session, commands: commands, keymap: keymap, modal: preset.isModal, optionAsMeta: OptionAsMeta(rawValue: optionAsMeta), options: options, showMarkup: showMarkup, showLineNumbers: showLineNumbers, theme: theme, onAppCommand: perform, onExternal: runExternal, knownTags: { [index = workspace.index] in (try? index.tags()) ?? [] })
125            }
126            .safeAreaInset(edge: .bottom, spacing: 0) {
127                VStack(spacing: 0) {
128                    ModeLine(session: session, commands: commands, clock: clock, perform: perform)
129                    EchoArea(commands: commands)
130                }
131            }
132        } else {
133            ContentUnavailableView(
134                workspace.roots.isEmpty ? "Add a folder of org files" : "Choose a file",
135                systemImage: "doc.text",
136                description: Text(workspace.roots.isEmpty ? "File ▸ Add Folder… (⇧⌘O)" : "Or press ⌘P to open one by name.")
137            )
138        }
139    }
140
141    @ToolbarContentBuilder
142    private var toolbarItems: some ToolbarContent {
143        ToolbarItem(placement: .navigation) {
144            Button(outlineShown ? "Hide Outline" : "Show Outline", systemImage: "list.bullet.indent") { toggleOutline() }
145                .help(outlineShown ? "Hide the outline (⌥⌘O)" : "Show the outline (⌥⌘O)")
146                .disabled(!query.isEmpty || previewPath != nil || session.path == nil)
147        }
148        if workspace.isIndexing {
149            ToolbarItem { ProgressView().controlSize(.small) }
150        }
151        if let running = clock.running {
152            ToolbarItem {
153                Menu {
154                    Button("Clock Out") { perform("app.clock.out") }
155                    Button("Cancel Clock") { perform("app.clock.cancel") }
156                    Button("Go to Clocked Entry") { perform("app.clock.goto") }
157                    Divider()
158                    Button("Clock In to Recent Entry…") { perform("app.clock.in-recent") }
159                    Button("Go to Recent Clocked Entry…") { perform("app.clock.goto-recent") }
160                    RecentClocks(clock: clock) { perform($0) }
161                } label: {
162                    TimelineView(.periodic(from: .now, by: 30)) { context in
163                        Text("⏱ \(running.heading) \(clockElapsed(running, now: context.date))").lineLimit(1)
164                    }
165                }
166                .help("Clocked in since \(running.startedAt.formatted(date: .omitted, time: .shortened))")
167            }
168        }
169        if session.conflict != nil {
170            ToolbarItem {
171                Button("Conflict", systemImage: "exclamationmark.triangle") { commands.showingConflict = true }
172                    .help("The file changed on disk, and the changes conflict with yours")
173            }
174        }
175    }
176
177    private var main: some View {
178        NavigationSplitView {
179            Sidebar(workspace: workspace, session: session, selection: $selectedFile) { commands.showingFolderPicker = true }
180                .navigationSplitViewColumnWidth(min: 200, ideal: 260)
181        } detail: {
182            HStack(spacing: 0) {
183                if outlineShown {
184                    Group {
185                        if query.isEmpty {
186                            VStack(spacing: 0) {
187                                OutlineColumn(session: session)
188                                if backlinksShown, session.isOrg {
189                                    Divider()
190                                    BacklinksPane(workspace: workspace, session: session, commands: commands) { location in
191                                        selectedFile = location.path
192                                        session.show(location)
193                                    }
194                                    .frame(height: 200)
195                                }
196                            }
197                        } else {
198                            SearchResults(results: workspace.search(query, overlay: workspace.overlay(session.openDocuments))) { location in
199                                selectedFile = location.path
200                                session.show(location)
201                            }
202                        }
203                    }
204                    .frame(width: CGFloat(outlineWidth))
205                    PaneDivider(width: $outlineWidth, range: 160...400)
206                }
207                detail
208                    .frame(maxWidth: .infinity)
209                    .inspector(isPresented: $inspectorShown) {
210                        InspectorPane(session: session, commands: commands)
211                            .inspectorColumnWidth(min: 240, ideal: 340, max: 600)
212                    }
213            }
214        }
215        .navigationTitle(previewPath.map { ($0 as NSString).lastPathComponent } ?? session.path.map(session.bufferName) ?? "orgstar")
216        .navigationSubtitle(session.isReadOnly ? "Read-only: not UTF-8" : "")
217        .searchable(text: $query, placement: .toolbar, prompt: "Search notes")
218        .searchFocused($searchFocused)
219        .toolbar { toolbarItems }
220        .onChange(of: session.path) { plainOutlineShown = false }
221        .onChange(of: ScanRules(hiddenFiles: showHiddenFiles, ignoredFolders: Set(ignoredFolders.split(separator: " ").map(String.init))), initial: true) { _, rules in
222            workspace.scanRules = rules
223        }
224        .onChange(of: selectedFile) { old, path in
225            guard let path else { return }
226            if !DocumentSession.isOrgPath(path), !FileTypes.isText(path) {
227                previewPath = path
228                return
229            }
230            previewPath = nil
231            guard path != session.path else { return }
232            session.open(path)
233        }
234        .onChange(of: session.path) {
235            // Buffers switched by keys show in the sidebar too; a restored caret shows once.
236            if let path = session.path, selectedFile != path { selectedFile = path }
237            if let path = session.path, let caret = pendingCarets.removeValue(forKey: path) { session.reveal(caret) }
238            BufferRestore.save(session)
239            // Syncthing's conflict copies of the file.
240            let copies = session.syncConflictCopies().count
241            if copies > 0 { commands.show("\(copies) sync conflict \(copies == 1 ? "copy" : "copies") of this file; Resolve Sync Conflicts compares them.") }
242        }
243        .onChange(of: session.openPaths) { BufferRestore.save(session) }
244        .onChange(of: saveMode, initial: true) { _, mode in session.saveMode = mode }
245        .onChange(of: options, initial: true) { _, options in session.options = options }
246        .onChange(of: preset, initial: true) { loadKeymap() }
247        .sheet(isPresented: $showingImport) { EmacsImportView(workspace: workspace) }
248        .sheet(item: $panel) { panel in
249            switch panel {
250            case .columns(_, let view):
251                ColumnViewSheet(view: view) { offset in commands.editor?.reveal(offset) }
252            case .export(_, let source):
253                ExportSheet(source: source, inSubtree: exportSubtreeAvailable, target: exportTarget) { format, destination, open, subtree, bodyOnly in
254                    export(format, to: destination, open: open, subtree: subtree, bodyOnly: bodyOnly)
255                }
256            case .conflict:
257                ConflictSheet(session: session)
258            case .syncCopies:
259                SyncConflictSheet(session: session) { commands.show($0) }
260            case .recovery:
261                RecoverySheet(session: session) { commands.show($0) }
262            }
263        }
264        .sheet(item: $blockEdit) { request in
265            BlockEditorView(edit: request.edit) { content in
266                blockEdit = nil
267                guard let content else { return }
268                commands.editor?.perform(ReplaceBlockLines(edit: request.edit, content: content))
269            }
270        }
271        .sheet(isPresented: $commands.showingPalette) {
272            PaletteView(commands: commands) { id in
273                commands.showingPalette = false
274                // After the sheet closes, so app commands can present their own.
275                DispatchQueue.main.async { perform(id) }
276            }
277        }
278        .onChange(of: session.conflict) { _, conflict in
279            if conflict != nil { commands.showingConflict = true }
280        }
281        .onChange(of: commands.showingConflict) { _, showing in
282            guard showing else { return }
283            commands.showingConflict = false
284            if session.conflict != nil { panel = .conflict(UUID()) }
285        }
286        .onChange(of: workspace.changedFile?.version) {
287            if let path = workspace.changedFile?.path { session.fileChanged(path) }
288        }
289    }
290
291    var body: some View {
292        main
293        .onChange(of: ClockMenuState(running: clock.running, history: clock.history), initial: true) { _, state in
294            if statusItem == nil { statusItem = ClockStatusItem { commands.run($0) } }
295            statusItem?.update(state.running, recent: state.history.map(\.title))
296        }
297        .onChange(of: globalCapture, initial: true) { _, enabled in
298            hotKey?.unregister()
299            hotKey = enabled ? GlobalHotKey { perform("app.capture") } : nil
300        }
301        .onChange(of: commands.runRequest?.serial) {
302            if let id = commands.runRequest?.id { perform(id) }
303        }
304        .onChange(of: ConfigSync.shared.problems, initial: true) { _, problems in
305            if let first = problems.first {
306                commands.show(first + (problems.count > 1 ? " (and \(problems.count - 1) more)" : ""))
307            }
308        }
309        .onChange(of: ConfigSync.shared.changedFile?.serial) {
310            if ConfigSync.shared.changedFile?.name == "keymap.toml" { loadKeymap() }
311        }
312        .onChange(of: commands.jumpRequest?.id) {
313            guard let request = commands.jumpRequest else { return }
314            if request.path != session.path {
315                session.open(request.path)
316                selectedFile = request.path
317            }
318            session.reveal(request.offset)
319        }
320        .onChange(of: commands.focusSearch) { _, focus in
321            if focus {
322                searchFocused = true
323                commands.focusSearch = false
324            }
325        }
326        .fileImporter(isPresented: $commands.showingFolderPicker, allowedContentTypes: [.folder]) { result in
327            guard case .success(let url) = result else { return }
328            Task {
329                do { try await workspace.addRoot(url) } catch { workspace.lastError = error.localizedDescription }
330            }
331        }
332        .sheet(isPresented: $commands.showingQuickOpen) {
333            QuickOpenView(workspace: workspace) { entry in
334                selectedFile = entry.path
335                commands.showingQuickOpen = false
336            }
337        }
338        .alert("orgstar", isPresented: errorShown) {
339            Button("OK") {
340                workspace.lastError = nil
341                session.lastError = nil
342            }
343        } message: {
344            Text(workspace.lastError ?? session.lastError ?? "")
345        }
346        .task(id: ReminderKey(
347            enabled: remindersEnabled, lead: reminderLead, subfolders: agendaSubfolders, files: workspace.files.count,
348            changed: workspace.changedFile?.version, edits: session.editVersion, hour: hour
349        )) {
350            await updateReminders()
351        }
352        .task {
353            while !Task.isCancelled {
354                try? await Task.sleep(for: .seconds(3600))
355                hour += 1
356            }
357        }
358        // `org-resolve-clocks-if-idle`, checked every minute while a clock runs.
359        .task(id: "\(clock.running?.start ?? "") \(clockIdleTime)") {
360            guard clock.running != nil, clockIdleTime > 0 else { return }
361            while !Task.isCancelled {
362                try? await Task.sleep(for: .seconds(60))
363                guard !Task.isCancelled, clock.running != nil, !clock.isResolving else { continue }
364                let idle = ClockIdle.seconds()
365                guard idle > Double(clockIdleTime * 60) else { continue }
366                NSApp.requestUserAttention(.informationalRequest)
367                report(await clock.resolveIdle(session, idleSince: Date().addingTimeInterval(-idle), ask: askClock))
368            }
369        }
370        .task {
371            DevelopmentHooks.scheduleSnapshot()
372            pendingCarets = BufferRestore.restore(session)
373            if let path = session.path, let caret = pendingCarets.removeValue(forKey: path) { session.reveal(caret) }
374            // Files handed over at launch open after the restored buffers, and show.
375            for path in AppDelegate.pendingOpens { session.open(path) }
376            AppDelegate.pendingOpens = []
377            for link in AppDelegate.pendingLinks + [DevelopmentHooks.urlToOpen].compactMap({ $0 }) { commands.handle(protocolURL: link) }
378            AppDelegate.pendingLinks = []
379            if let path = DevelopmentHooks.fileToOpen { selectedFile = path }
380            if let root = DevelopmentHooks.rootToAdd { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
381            if let commandList = DevelopmentHooks.commandToRun {
382                // The file opened above needs its editor first.
383                for _ in 0..<20 where DevelopmentHooks.fileToOpen != nil && commands.editor == nil { try? await Task.sleep(for: .milliseconds(100)) }
384                for command in commandList.split(separator: ",") { perform(String(command)) }
385                for answer in DevelopmentHooks.answers {
386                    for _ in 0..<20 where commands.prompt == nil { try? await Task.sleep(for: .milliseconds(100)) }
387                    commands.answer(answer)
388                }
389            }
390            if let id = DevelopmentHooks.windowToOpen {
391                if id == "settings" { openSettings() } else { openWindow(id: id) }
392            }
393            await workspace.refresh()
394            workspace.startWatching()
395        }
396    }
397
398    /// The selection, or the whole file without one, on the clipboard as HTML, RTF and plain
399    /// text, to paste formatted into mail and documents.
400    private func copyRichText() {
401        guard let path = session.path, let whole = session.document?.text, let editor = commands.editor else { return commands.show("No file is open") }
402        let defaults = Preferences.orgSettings.resolvingSetupFiles(in: whole, path: path, read: OrgSettings.readFile)
403        let selection = editor.context().selection.first { !$0.isEmpty }
404        let selected = selection.map { (whole as NSString).substring(with: NSRange($0)) }
405        let url = URL(fileURLWithPath: path)
406        let html = HTMLExport.page(
407            selected ?? whole, fallbackTitle: url.deletingPathExtension().lastPathComponent, settings: defaults, path: path, bodyOnly: selected != nil,
408            codeStyle: HTMLCodeStyle(highlighter: EditorView.highlighter, theme: theme)
409        )
410        do {
411            try RichTextExport.copy(html: html, directory: url.deletingLastPathComponent())
412            commands.show(selected == nil ? "Copied the file as rich text" : "Copied the selection as rich text")
413        } catch {
414            commands.show("\(error)")
415        }
416    }
417
418    /// Whether the caret is in a heading's subtree, which the export dialog can export alone.
419    private var exportSubtreeAvailable: Bool {
420        guard let text = session.document?.text, let caret = commands.editor?.context().caret else { return false }
421        return ExportScope.subtree(text, at: caret) != nil
422    }
423
424    /// Where an export goes by default: `#+EXPORT_FILE_NAME`, or the subtree's
425    /// `EXPORT_FILE_NAME`, else beside the file, with `ext`.
426    private func exportTarget(_ ext: String, subtree: Bool) -> URL {
427        let path = session.path ?? ""
428        let text = session.document?.text ?? ""
429        let caret = subtree ? commands.editor?.context().caret : nil
430        return ExportScope.output(for: URL(fileURLWithPath: path), name: ExportScope.fileName(text, subtreeAt: caret), extension: ext)
431    }
432
433    /// Writes the export where `#+EXPORT_FILE_NAME` says or beside the file, as Emacs's export
434    /// dispatcher does, or to `destination`, and opens it with `open`. `subtree` exports the
435    /// subtree at the caret alone; `bodyOnly` leaves out the title and page wrapper.
436    private func export(_ format: String, to destination: URL? = nil, open: Bool = false, subtree: Bool = false, bodyOnly: Bool = false) {
437        guard let path = session.path, var text = session.document?.text else {
438            commands.show("No file is open")
439            return
440        }
441        let url = URL(fileURLWithPath: path)
442        let base = url.deletingPathExtension()
443        let defaults = Preferences.orgSettings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
444        let open = open || format == "html-open"
445        let caret = commands.editor?.context().caret ?? 0
446        let whole = text
447        if subtree {
448            guard let narrowed = ExportScope.subtree(text, at: caret, settings: defaults) else { return commands.show("Not in a subtree") }
449            text = narrowed
450        }
451        switch format {
452        case "html", "html-open", "markdown":
453            let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
454            let target = destination ?? ExportScope.output(for: url, name: name, extension: format == "markdown" ? "md" : "html")
455            let content = format == "markdown"
456                ? MarkdownExport.document(text, settings: defaults, path: path, bodyOnly: bodyOnly)
457                : HTMLExport.page(
458                    text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path, bodyOnly: bodyOnly,
459                    codeStyle: HTMLCodeStyle(highlighter: EditorView.highlighter, theme: theme)
460                )
461            do {
462                try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
463                try content.write(to: target, atomically: true, encoding: .utf8)
464                commands.show("Exported to \(target.lastPathComponent)")
465                if open { NSWorkspace.shared.open(target) }
466            } catch {
467                commands.show("Can't write \(target.lastPathComponent): \(error.localizedDescription)")
468            }
469        case "print-pdf", "docx", "rtf", "plain-text":
470            let ext = ["print-pdf": "pdf", "plain-text": "txt"][format] ?? format
471            let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
472            let target = destination ?? ExportScope.output(for: url, name: name, extension: ext)
473            let html = HTMLExport.page(
474                text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path,
475                codeStyle: HTMLCodeStyle(highlighter: EditorView.highlighter, theme: theme)
476            )
477            let directory = url.deletingLastPathComponent()
478            if format == "print-pdf" { commands.show("Exporting to PDF…") }
479            Task {
480                do {
481                    let data: Data
482                    switch format {
483                    case "print-pdf": data = try await PDFExport.pdf(html: html, directory: directory)
484                    case "docx": data = try RichTextExport.docx(RichTextExport.attributed(html: html, directory: directory))
485                    case "rtf": data = try RichTextExport.rtf(RichTextExport.attributed(html: html, directory: directory))
486                    default: data = Data(RichTextExport.plain(try RichTextExport.attributed(html: html, directory: directory)).utf8)
487                    }
488                    try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
489                    try data.write(to: target, options: .atomic)
490                    commands.show("Exported to \(target.lastPathComponent)")
491                    if open { NSWorkspace.shared.open(target) }
492                } catch {
493                    commands.show("Can't export \(target.lastPathComponent): \(error)")
494                }
495            }
496        default:
497            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"]
498            guard let function = functions[format] else { return }
499            commands.show("Exporting with Emacs…")
500            commands.runInEmacs {
501                do {
502                    // Emacs narrows to the subtree and reads EXPORT_FILE_NAME itself.
503                    let point = subtree ? (whole as NSString).substring(to: min(caret, (whole as NSString).length)).unicodeScalars.count + 1 : nil
504                    var written = URL(fileURLWithPath: try await EmacsRunner.export(
505                        text: whole, path: path, function: function, subtree: point, bodyOnly: bodyOnly
506                    ))
507                    if let destination, destination.standardizedFileURL != written.standardizedFileURL {
508                        try? FileManager.default.removeItem(at: destination)
509                        try FileManager.default.moveItem(at: written, to: destination)
510                        written = destination
511                    }
512                    commands.show("Exported to \(written.lastPathComponent)")
513                    if open { NSWorkspace.shared.open(written) }
514                } catch is CancellationError {
515                    commands.show("Export canceled")
516                } catch {
517                    commands.show("\(error)")
518                }
519            }
520        }
521    }
522
523    /// Work a command hands to the platform: tables recalculated in Emacs.
524    private func runExternal(_ request: ExternalRequest) {
525        switch request {
526        case .openLink(let link):
527            if let message = LinkOpener.open(link, session: session, workspace: workspace) { commands.show(message) }
528        case .tangle(let scope):
529            commands.show(session.tangle(scope))
530        case .agenda(let start, let days):
531            commands.agendaRequest = (start, days)
532            openWindow(id: "agenda")
533        case .editBlock(let edit):
534            blockEdit = BlockEditRequest(edit: edit)
535        case .columnView(let view):
536            panel = .columns(UUID(), view)
537        case .emacsTable(let table, let point, let form, let reason, let lisp):
538            let run = {
539                commands.show("Recalculating in Emacs (\(reason))…")
540                commands.runInEmacs { commands.show(await session.recalculateInEmacs(table: table, point: point, form: form)) }
541            }
542            guard lisp, let path = session.path, let text = session.document?.text else { return run() }
543            let content = (text as NSString).substring(with: NSRange(location: table.lowerBound, length: min((text as NSString).length, table.upperBound + 2000) - table.lowerBound))
544            if trust.isTrusted(path: path, content: content) { return run() }
545            commands.ask(Prompt(key: "confirm", message: "This table's formulas run Lisp. Run them? (yes, no, always)", choices: ["yes", "no", "always"])) { answer in
546                switch answer {
547                case "always":
548                    trust.trust(path: path, content: content)
549                    run()
550                case "yes": run()
551                default: commands.show("Not recalculated")
552                }
553            }
554        case .babel(let job):
555            let run = {
556                commands.show("Running \(job.language) block… (⌘. to cancel)")
557                session.startBabel(job) { commands.show($0) }
558            }
559            guard let path = session.path else { return }
560            if !job.alwaysAsk, trust.isTrusted(path: path, content: job.blockText) { return run() }
561            let choices = job.alwaysAsk ? ["yes", "no"] : ["yes", "no", "always"]
562            commands.ask(Prompt(key: "confirm", message: "Run this \(job.language) block? (\(choices.joined(separator: ", ")))", choices: choices)) { answer in
563                switch answer {
564                case "always":
565                    trust.trust(path: path, content: job.blockText)
566                    run()
567                case "yes": run()
568                default: commands.show("Not run")
569                }
570            }
571        }
572    }
573
574    private struct ReminderKey: Hashable {
575        var enabled: Bool
576        var lead: Int
577        var subfolders: Bool
578        var files: Int
579        var changed: Int?
580        var edits: Int
581        var hour: Int
582    }
583
584    /// Sets the notifications for the next week's timed entries, once edits pause.
585    private func updateReminders() async {
586        guard let scheduler else { return }
587        guard remindersEnabled else {
588            await scheduler.clear()
589            return
590        }
591        try? await Task.sleep(for: .seconds(2))
592        guard !Task.isCancelled, !workspace.files.isEmpty else { return }
593        let agenda = reminderAgenda ?? AgendaModel(workspace: workspace)
594        reminderAgenda = agenda
595        agenda.includeSubfolders = agendaSubfolders
596        let open = session.openTexts
597        let reminders = await agenda.reminders(open: open, lead: reminderLead)
598        guard !Task.isCancelled else { return }
599        await scheduler.reconcile(reminders)
600    }
601
602    private func loadKeymap() {
603        let loaded = KeymapLoader.load(preset, commands: Set(EditorCommands.all.map(\.id)))
604        keymap = loaded.keymap
605        commands.keymap = loaded.keymap
606        commands.modal = preset.isModal
607        if let first = loaded.problems.first {
608            let more = loaded.problems.count > 1 ? " (and \(loaded.problems.count - 1) more)" : ""
609            commands.show("keymap.toml: \(first)\(more)")
610        }
611    }
612
613    /// `SPC b b`: open buffers, most recent first, by name (with the folder when names repeat).
614    private func switchBuffer() {
615        let paths = session.recentPaths.dropFirst() + session.recentPaths.prefix(1)
616        let labels = paths.map(session.bufferName)
617        guard !labels.isEmpty else { return commands.show("No buffers are open") }
618        commands.ask(Prompt(key: "buffer", message: "Switch to buffer:", choices: labels)) { answer in
619            guard let answer, let index = labels.firstIndex(of: answer) else { return }
620            session.open(Array(paths)[index])
621        }
622    }
623
624    /// Runs a command from a key, the palette or the Org menu.
625    private func perform(_ id: String) {
626        let orgOnly = ["app.refile", "app.archive", "app.clock.in", "app.clock.default", "app.copy-rich-text"].contains(id) || id.hasPrefix("app.export.") || id.hasPrefix("org.")
627        if orgOnly, !session.isOrg {
628            commands.show("Not an org file")
629            return
630        }
631        switch id {
632        case "app.save":
633            if !session.save(), session.conflict != nil { commands.showingConflict = true }
634        case "app.quit": NSApp.terminate(nil)
635        case "app.save-all":
636            if !session.saveAll(), session.conflict != nil { commands.showingConflict = true }
637        case "app.buffer.switch": switchBuffer()
638        case "app.buffer.next": session.cycle(1)
639        case "app.buffer.previous": session.cycle(-1)
640        case "app.buffer.last": session.showPrevious()
641        case "app.buffer.kill":
642            guard let path = session.path else {
643                NSApp.keyWindow?.performClose(nil)
644                return
645            }
646            if UnsavedChanges.resolve(session) { session.kill(path) }
647        case "app.buffer.kill-others":
648            let others = session.openPaths.filter { $0 != session.path }
649            if UnsavedChanges.resolve(session, paths: others) { others.forEach(session.kill) }
650        case "app.buffer.kill-all":
651            let all = session.openPaths
652            if UnsavedChanges.resolve(session, paths: all) { all.forEach(session.kill) }
653        case "app.toggle-tab-bar": showTabBar.toggle()
654        case "app.babel.cancel":
655            if session.isRunningBabel {
656                session.cancelBabel()
657            } else if let task = commands.emacsTask {
658                task.cancel()
659            } else {
660                commands.show("Nothing is running")
661            }
662        case "app.toggle-outline": toggleOutline()
663        case "app.toggle-backlinks": backlinksShown.toggle()
664        case "app.toggle-inspector": inspectorShown.toggle()
665        case "app.toggle-markup": showMarkup.toggle()
666        case "app.toggle-line-numbers": showLineNumbers.toggle()
667        case "app.import-emacs": showingImport = true
668        case "app.edit-config": commands.jump(path: UserConfig.configFile.path, offset: 0)
669        case "app.quick-open": commands.showingQuickOpen = true
670        case "app.palette": commands.showingPalette = true
671        case "app.search": commands.focusSearch = true
672        case "app.reload-keymap":
673            loadKeymap()
674            commands.show("Keymap reloaded")
675        case "app.refile":
676            let targets = workspace.refileTargets(openPath: session.path, document: session.document)
677            commands.ask(Prompt(key: "refile", message: "Refile to:", choices: targets.map(\.label))) { answer in
678                guard let answer, let target = targets.first(where: { $0.label == answer }) else { return }
679                if let message = session.refile(to: target) { commands.show(message) }
680            }
681        case "app.archive":
682            if let message = session.archive() { commands.show(message) }
683        case "app.table-import":
684            // `org-table-import`: a TSV, CSV or space-separated file becomes a table at point.
685            guard let editor = commands.editor else { return commands.show("No file is open") }
686            let panel = NSOpenPanel()
687            panel.allowedContentTypes = [.commaSeparatedText, .tabSeparatedText, .plainText]
688            guard panel.runModal() == .OK, let url = panel.url else { return }
689            guard let contents = try? String(contentsOf: url, encoding: .utf8) else { return commands.show("Can't read \(url.lastPathComponent)") }
690            editor.perform(ImportTable(contents: contents))
691        case "app.table-export":
692            // `org-table-export`: CSV for a .csv name, else TSV.
693            guard let editor = commands.editor else { return commands.show("No file is open") }
694            let context = editor.context()
695            guard ImportTable.exportText(context.text, at: context.caret, path: "") != nil else { return commands.show("No table at point") }
696            let panel = NSSavePanel()
697            panel.nameFieldStringValue = "table.csv"
698            guard panel.runModal() == .OK, let url = panel.url,
699                  let text = ImportTable.exportText(context.text, at: context.caret, path: url.path) else { return }
700            do {
701                try text.write(to: url, atomically: true, encoding: .utf8)
702                commands.show("Export done.")
703            } catch {
704                commands.show("File not written: \(error.localizedDescription)")
705            }
706        case "org.subtree.paste":
707            guard let text = NSPasteboard.general.string(forType: .string) else { return commands.show("The clipboard is empty") }
708            commands.editor?.perform(PasteSubtree(text: text))
709        case "org.link.insert":
710            commands.editor?.perform(InsertLink(stored: commands.storedLinks, file: session.path))
711        case "org.link.store":
712            guard let editor = commands.editor, let path = session.path else { return commands.show("No method for storing a link from this buffer") }
713            commands.storeLink(Links.store(in: editor.context(), path: Links.abbreviate(path, home: NSHomeDirectory())))
714        case "org.id.store-link":
715            guard let editor = commands.editor, let path = session.path else { return }
716            if case .commit = editor.perform(CreateID()),
717               let link = Links.storeID(in: editor.context(), fileName: (path as NSString).lastPathComponent) {
718                commands.storeLink(link)
719            }
720        case "app.agenda":
721            openWindow(id: "agenda")
722        case "app.clock.in":
723            clockIn(.caret)
724        case "app.clock.in-recent":
725            clockIn(.select)
726        case "app.clock.in-last":
727            clockIn(.last)
728        case let id where id.hasPrefix("app.clock.history."):
729            if let index = Int(id.dropFirst("app.clock.history.".count)), index < clock.history.count { clockIn(.task(clock.history[index])) }
730        case "app.clock.out":
731            commands.show(clock.clockOut(session))
732        case "app.clock.cancel":
733            commands.show(clock.clockOut(session, cancel: true))
734        case "app.clock.goto":
735            let found = clock.goto(session)
736            if let location = found.location { commands.jump(path: location.path, offset: location.offset) }
737            if let message = found.message { commands.show(message) }
738        case "app.clock.goto-recent":
739            Task {
740                let found = await clock.gotoRecent(session, ask: askClock)
741                if let location = found.location { commands.jump(path: location.path, offset: location.offset) }
742                if let message = found.message { commands.show(message) }
743            }
744        case "app.clock.default":
745            commands.show(clock.markDefault(session))
746        case "app.clock.resolve":
747            Task { report(await clock.resolveOpenClocks(session, paths: orgFiles, ask: askClock)) }
748        case "app.clock.report":
749            openWindow(id: "clock-report")
750        case "app.board":
751            openWindow(id: "board")
752        case "app.capture":
753            NSApp.activate()
754            openWindow(id: "capture")
755        case "app.revert":
756            // `:e`: the file as it is on disk; unsaved changes go to recovery.
757            guard session.path != nil else { return commands.show("No file is open") }
758            session.useDiskVersion()
759            commands.show("Reverted to the file on disk")
760        case "app.sync-conflicts":
761            guard session.path != nil else { return commands.show("No file is open") }
762            panel = .syncCopies(UUID())
763        case "app.recovery":
764            guard session.path != nil else { return commands.show("No file is open") }
765            panel = .recovery(UUID())
766        case "app.copy-rich-text":
767            copyRichText()
768        case "app.export-dialog":
769            guard let path = session.path else { return commands.show("No file is open") }
770            panel = .export(UUID(), URL(fileURLWithPath: path))
771        case let id where id.hasPrefix("app.export."):
772            export(String(id.dropFirst("app.export.".count)))
773        default:
774            if let editor = commands.editor { editor.run(id) } else { commands.show("No file is open") }
775        }
776    }
777
778    private var askClock: ClockModel.Ask { commands.askClock }
779
780    /// The files `org-resolve-clocks` looks through: the workspace's org files.
781    private var orgFiles: [String] { workspace.files.filter { $0.kind == .org }.map(\.path) }
782
783    private func clockIn(_ target: ClockModel.Target) {
784        Task { report(await clock.clockIn(session, target: target, paths: orgFiles, ask: askClock)) }
785    }
786
787    /// The last message of a clock command, and the clock to show for `j`.
788    private func report(_ outcome: ClockModel.Outcome) {
789        if let jump = outcome.jump { commands.jump(path: jump.path, offset: jump.offset) }
790        if let message = outcome.messages.last(where: { !$0.isEmpty }) { commands.show(message) }
791    }
792
793    private var errorShown: Binding<Bool> {
794        Binding(get: { workspace.lastError != nil || session.lastError != nil }, set: { _ in })
795    }
796}
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