Sources/Orgstar/ContentView.swift

848c7b130274052f194a17fccd4e33e6bb30851d
orgstar/Sources/Orgstar/ContentView.swift history · blame · raw

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