Sources/Orgstar/ContentView.swift

265b9d63623b99c4c2b8e8c4d104c57fec553586
orgstar/Sources/Orgstar/ContentView.swift history · blame · raw

893 lines · 42128 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("agendaSubfolders") private var agendaSubfolders = false
 20    @State private var reminderAgenda: AgendaModel?
 21    @State private var trust = TrustStore()
 22    @State private var hotKey: GlobalHotKey?
 23    @State private var statusItem: ClockStatusItem?
 24    @AppStorage("globalCapture") private var globalCapture = true
 25    @State private var hour = 0
 26    @AppStorage("saveMode") private var saveMode = SaveMode.automatic
 27    @AppStorage("keymap") private var preset = KeymapPreset.emacs
 28    @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
 29    @State private var keymap = KeymapPreset.emacs.keymap
 30    @AppStorage("tagsColumn") private var tagsColumn = -77
 31    @AppStorage("headingAfterSubtree") private var headingAfterSubtree = true
 32    @AppStorage("splitLine") private var splitLine = false
 33    @AppStorage("alphabeticalLists") private var alphabeticalLists = true
 34    @AppStorage("fillColumn") private var fillColumn = 80
 35    @AppStorage("hiddenMarkers") private var hiddenMarkers = true
 36    @AppStorage("prettyEntities") private var prettyEntities = true
 37    @AppStorage("logDone") private var logDone = "nil"
 38    @AppStorage("logIntoDrawer") private var logIntoDrawer = ""
 39    @AppStorage("logReschedule") private var logReschedule = "nil"
 40    @AppStorage("logRedeadline") private var logRedeadline = "nil"
 41    @AppStorage("useSpeedCommands") private var useSpeedCommands = false
 42    @AppStorage("startupWithInlineImages") private var startupWithInlineImages = false
 43    @AppStorage("startupIndented") private var startupIndented = true
 44    @AppStorage("hideLeadingStars") private var hideLeadingStars = false
 45    @AppStorage("startupAlignAllTables") private var startupAlignAllTables = false
 46    @AppStorage("hideDrawerStartup") private var hideDrawerStartup = true
 47    @AppStorage("hideBlockStartup") private var hideBlockStartup = false
 48
 49    private var options: EditingOptions {
 50        Preferences.options(
 51            tagsColumn: tagsColumn, headingAfterSubtree: headingAfterSubtree, splitLine: splitLine, alphabeticalLists: alphabeticalLists,
 52            fillColumn: fillColumn, hiddenMarkers: hiddenMarkers, prettyEntities: prettyEntities, logDone: logDone, logIntoDrawer: logIntoDrawer,
 53            hideDrawerStartup: hideDrawerStartup, hideBlockStartup: hideBlockStartup, logReschedule: logReschedule, logRedeadline: logRedeadline,
 54            useSpeedCommands: useSpeedCommands, startupWithInlineImages: startupWithInlineImages,
 55            startupIndented: startupIndented, hideLeadingStars: hideLeadingStars, startupAlignAllTables: startupAlignAllTables
 56        )
 57    }
 58    /// A block being edited apart (`org-edit-special`).
 59    @State private var blockEdit: BlockEditRequest?
 60    /// A sheet a command opened: column view or the export dialog.
 61    @State private var panel: Panel?
 62
 63    @State private var selectedFile: String?
 64    /// A file that isn't text, shown as a preview instead of the open document.
 65    @State private var previewPath: String?
 66    @AppStorage("outlineShown") private var orgOutlineShown = true
 67    @AppStorage("outlineWidth") private var outlineWidth = 220.0
 68    @AppStorage("showMarkup") private var showMarkup = false
 69    @AppStorage("showLineNumbers") private var showLineNumbers = true
 70    @AppStorage("showHiddenFiles") private var showHiddenFiles = true
 71    @AppStorage("ignoredFolders") private var ignoredFolders = ScanRules.defaultIgnoredFolders.sorted().joined(separator: " ")
 72    @AppStorage("themeFont") private var themeFont = ""
 73    @AppStorage("themeFontSize") private var themeFontSize = 13
 74    @AppStorage("themeLineSpacing") private var themeLineSpacing = 2
 75    @AppStorage("themeHeadingStep") private var themeHeadingStep = 1
 76
 77    /// The theme's colors from config.toml with the type settings.
 78    private var theme: ThemeSpec {
 79        var spec = ConfigSync.shared.theme
 80        spec.font = themeFont
 81        spec.fontSize = themeFontSize
 82        spec.lineSpacing = themeLineSpacing
 83        spec.headingSizeStep = themeHeadingStep
 84        return spec
 85    }
 86    /// The outline for a file that isn't org, off until asked for.
 87    @State private var plainOutlineShown = false
 88    @State private var showingImport = false
 89    @AppStorage("showTabBar") private var showTabBar = false
 90    /// Carets of restored buffers, shown when each first shows.
 91    @State private var pendingCarets: [String: Int] = [:]
 92    @State private var query = ""
 93    @FocusState private var searchFocused: Bool
 94    @Environment(\.openWindow) private var openWindow
 95    @Environment(\.openSettings) private var openSettings
 96
 97    /// Whether the outline pane shows: remembered for org files, hidden by default for
 98    /// other files, and always shown while search results are up.
 99    private var outlineShown: Bool {
100        !query.isEmpty || (previewPath == nil && (session.isOrg ? orgOutlineShown : plainOutlineShown))
101    }
102
103    private func toggleOutline() {
104        if session.isOrg { orgOutlineShown.toggle() } else { plainOutlineShown.toggle() }
105    }
106
107    @ViewBuilder
108    private var detail: some View {
109        if let previewPath {
110            FilePreview(path: previewPath)
111        } else if session.path != nil {
112            VStack(spacing: 0) {
113                if showTabBar { BufferTabs(session: session) }
114                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()) ?? [] })
115            }
116            .safeAreaInset(edge: .bottom, spacing: 0) {
117                VStack(spacing: 0) {
118                    ModeLine(session: session, commands: commands, clock: clock, perform: perform)
119                    EchoArea(commands: commands)
120                }
121            }
122        } else {
123            ContentUnavailableView(
124                workspace.roots.isEmpty ? "Add a folder of org files" : "Choose a file",
125                systemImage: "doc.text",
126                description: Text(workspace.roots.isEmpty ? "File ▸ Add Folder… (⇧⌘O)" : "Or press ⌘P to open one by name.")
127            )
128        }
129    }
130
131    @ToolbarContentBuilder
132    private var toolbarItems: some ToolbarContent {
133        ToolbarItem(placement: .navigation) {
134            Button(outlineShown ? "Hide Outline" : "Show Outline", systemImage: "list.bullet.indent") { toggleOutline() }
135                .help(outlineShown ? "Hide the outline (⌥⌘O)" : "Show the outline (⌥⌘O)")
136                .disabled(!query.isEmpty || previewPath != nil || session.path == nil)
137        }
138        if workspace.isIndexing {
139            ToolbarItem { ProgressView().controlSize(.small) }
140        }
141        if let running = clock.running {
142            ToolbarItem {
143                Menu {
144                    Button("Clock Out") { perform("app.clock.out") }
145                    Button("Cancel Clock") { perform("app.clock.cancel") }
146                    Button("Go to Clocked Entry") { perform("app.clock.goto") }
147                } label: {
148                    TimelineView(.periodic(from: .now, by: 30)) { context in
149                        Text("⏱ \(running.heading) \(clockElapsed(running, now: context.date))").lineLimit(1)
150                    }
151                }
152                .help("Clocked in since \(running.startedAt.formatted(date: .omitted, time: .shortened))")
153            }
154        }
155        if session.conflict != nil {
156            ToolbarItem {
157                Button("Conflict", systemImage: "exclamationmark.triangle") { commands.showingConflict = true }
158                    .help("The file changed on disk, and the changes conflict with yours")
159            }
160        }
161    }
162
163    private var main: some View {
164        NavigationSplitView {
165            Sidebar(workspace: workspace, session: session, selection: $selectedFile) { commands.showingFolderPicker = true }
166                .navigationSplitViewColumnWidth(min: 200, ideal: 260)
167        } detail: {
168            HStack(spacing: 0) {
169                if outlineShown {
170                    Group {
171                        if query.isEmpty {
172                            OutlineColumn(session: session)
173                        } else {
174                            SearchResults(results: workspace.search(query, overlay: workspace.overlay(session.openDocuments))) { location in
175                                selectedFile = location.path
176                                session.show(location)
177                            }
178                        }
179                    }
180                    .frame(width: CGFloat(outlineWidth))
181                    PaneDivider(width: $outlineWidth, range: 160...400)
182                }
183                detail
184                    .frame(maxWidth: .infinity)
185            }
186        }
187        .navigationTitle((previewPath ?? session.path).map { ($0 as NSString).lastPathComponent } ?? "Orgstar")
188        .navigationSubtitle(session.isReadOnly ? "Read-only: not UTF-8" : "")
189        .searchable(text: $query, placement: .toolbar, prompt: "Search notes")
190        .searchFocused($searchFocused)
191        .toolbar { toolbarItems }
192        .onChange(of: session.path) { plainOutlineShown = false }
193        .onChange(of: ScanRules(hiddenFiles: showHiddenFiles, ignoredFolders: Set(ignoredFolders.split(separator: " ").map(String.init))), initial: true) { _, rules in
194            workspace.scanRules = rules
195        }
196        .onChange(of: selectedFile) { old, path in
197            guard let path else { return }
198            if !DocumentSession.isOrgPath(path), !FileTypes.isText(path) {
199                previewPath = path
200                return
201            }
202            previewPath = nil
203            guard path != session.path else { return }
204            session.open(path)
205        }
206        .onChange(of: session.path) {
207            // Buffers switched by keys show in the sidebar too; a restored caret shows once.
208            if let path = session.path, selectedFile != path { selectedFile = path }
209            if let path = session.path, let caret = pendingCarets.removeValue(forKey: path) { session.reveal(caret) }
210            BufferRestore.save(session)
211        }
212        .onChange(of: session.openPaths) { BufferRestore.save(session) }
213        .onChange(of: saveMode, initial: true) { _, mode in session.saveMode = mode }
214        .onChange(of: options, initial: true) { _, options in session.options = options }
215        .onChange(of: preset, initial: true) { loadKeymap() }
216        .sheet(isPresented: $showingImport) { EmacsImportView(workspace: workspace) }
217        .sheet(item: $panel) { panel in
218            switch panel {
219            case .columns(_, let view):
220                ColumnViewSheet(view: view) { offset in commands.editor?.reveal(offset) }
221            case .export(_, let source):
222                ExportSheet(source: source) { format, destination, open in export(format, to: destination, open: open) }
223            }
224        }
225        .sheet(item: $blockEdit) { request in
226            BlockEditorView(edit: request.edit) { content in
227                blockEdit = nil
228                guard let content else { return }
229                commands.editor?.perform(ReplaceBlockLines(edit: request.edit, content: content))
230            }
231        }
232        .sheet(isPresented: $commands.showingPalette) {
233            PaletteView(commands: commands) { id in
234                commands.showingPalette = false
235                // After the sheet closes, so app commands can present their own.
236                DispatchQueue.main.async { perform(id) }
237            }
238        }
239        .onChange(of: session.conflict) { _, conflict in
240            if conflict != nil { commands.showingConflict = true }
241        }
242        .alert("Conflicting changes", isPresented: $commands.showingConflict) {
243            Button("Keep Mine") { session.keepMine() }
244            Button("Use Disk Version") { session.useDiskVersion() }
245            Button("Decide Later", role: .cancel) {}
246        } message: {
247            Text((session.conflict ?? "") + " The version you don't keep is saved in the recovery folder.")
248        }
249        .onChange(of: workspace.changedFile?.version) {
250            if let path = workspace.changedFile?.path { session.fileChanged(path) }
251        }
252    }
253
254    var body: some View {
255        main
256        .onChange(of: clock.running, initial: true) { _, running in
257            if statusItem == nil { statusItem = ClockStatusItem { commands.run($0) } }
258            statusItem?.update(running)
259        }
260        .onChange(of: globalCapture, initial: true) { _, enabled in
261            hotKey?.unregister()
262            hotKey = enabled ? GlobalHotKey { perform("app.capture") } : nil
263        }
264        .onChange(of: commands.runRequest?.serial) {
265            if let id = commands.runRequest?.id { perform(id) }
266        }
267        .onChange(of: ConfigSync.shared.problems, initial: true) { _, problems in
268            if let first = problems.first {
269                commands.show(first + (problems.count > 1 ? " (and \(problems.count - 1) more)" : ""))
270            }
271        }
272        .onChange(of: ConfigSync.shared.changedFile?.serial) {
273            if ConfigSync.shared.changedFile?.name == "keymap.toml" { loadKeymap() }
274        }
275        .onChange(of: commands.jumpRequest?.id) {
276            guard let request = commands.jumpRequest else { return }
277            if request.path != session.path {
278                session.open(request.path)
279                selectedFile = request.path
280            }
281            session.reveal(request.offset)
282        }
283        .onChange(of: commands.focusSearch) { _, focus in
284            if focus {
285                searchFocused = true
286                commands.focusSearch = false
287            }
288        }
289        .fileImporter(isPresented: $commands.showingFolderPicker, allowedContentTypes: [.folder]) { result in
290            guard case .success(let url) = result else { return }
291            Task {
292                do { try await workspace.addRoot(url) } catch { workspace.lastError = error.localizedDescription }
293            }
294        }
295        .sheet(isPresented: $commands.showingQuickOpen) {
296            QuickOpenView(workspace: workspace) { entry in
297                selectedFile = entry.path
298                commands.showingQuickOpen = false
299            }
300        }
301        .alert("Orgstar", isPresented: errorShown) {
302            Button("OK") {
303                workspace.lastError = nil
304                session.lastError = nil
305            }
306        } message: {
307            Text(workspace.lastError ?? session.lastError ?? "")
308        }
309        .task(id: ReminderKey(
310            enabled: remindersEnabled, lead: reminderLead, subfolders: agendaSubfolders, files: workspace.files.count,
311            changed: workspace.changedFile?.version, edits: session.editVersion, hour: hour
312        )) {
313            await updateReminders()
314        }
315        .task {
316            while !Task.isCancelled {
317                try? await Task.sleep(for: .seconds(3600))
318                hour += 1
319            }
320        }
321        .task {
322            DevelopmentHooks.scheduleSnapshot()
323            pendingCarets = BufferRestore.restore(session)
324            if let path = session.path, let caret = pendingCarets.removeValue(forKey: path) { session.reveal(caret) }
325            // Files handed over at launch open after the restored buffers, and show.
326            for path in AppDelegate.pendingOpens { session.open(path) }
327            AppDelegate.pendingOpens = []
328            if let path = DevelopmentHooks.fileToOpen { selectedFile = path }
329            if let root = DevelopmentHooks.rootToAdd { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
330            if let commandList = DevelopmentHooks.commandToRun {
331                // The file opened above needs its editor first.
332                for _ in 0..<20 where DevelopmentHooks.fileToOpen != nil && commands.editor == nil { try? await Task.sleep(for: .milliseconds(100)) }
333                for command in commandList.split(separator: ",") { perform(String(command)) }
334                for answer in DevelopmentHooks.answers {
335                    for _ in 0..<20 where commands.prompt == nil { try? await Task.sleep(for: .milliseconds(100)) }
336                    commands.answer(answer)
337                }
338            }
339            if let id = DevelopmentHooks.windowToOpen {
340                if id == "settings" { openSettings() } else { openWindow(id: id) }
341            }
342            await workspace.refresh()
343            workspace.startWatching()
344        }
345    }
346
347    /// Writes the export beside the file, as Emacs's export dispatcher does, or to
348    /// `destination`, and opens it with `open`.
349    private func export(_ format: String, to destination: URL? = nil, open: Bool = false) {
350        guard let path = session.path, let text = session.document?.text else {
351            commands.show("No file is open")
352            return
353        }
354        let url = URL(fileURLWithPath: path)
355        let base = url.deletingPathExtension()
356        let defaults = Preferences.orgSettings
357        let open = open || format == "html-open"
358        switch format {
359        case "html", "html-open", "markdown":
360            let target = destination ?? base.appendingPathExtension(format == "markdown" ? "md" : "html")
361            let content = format == "markdown"
362                ? MarkdownExport.document(text, settings: defaults)
363                : HTMLExport.page(text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path)
364            do {
365                try content.write(to: target, atomically: true, encoding: .utf8)
366                commands.show("Exported to \(target.lastPathComponent)")
367                if open { NSWorkspace.shared.open(target) }
368            } catch {
369                commands.show("Can't write \(target.lastPathComponent): \(error.localizedDescription)")
370            }
371        default:
372            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"]
373            guard let function = functions[format] else { return }
374            commands.show("Exporting with Emacs…")
375            Task {
376                do {
377                    var written = URL(fileURLWithPath: try await EmacsRunner.export(text: text, path: path, function: function))
378                    if let destination, destination.standardizedFileURL != written.standardizedFileURL {
379                        try? FileManager.default.removeItem(at: destination)
380                        try FileManager.default.moveItem(at: written, to: destination)
381                        written = destination
382                    }
383                    commands.show("Exported to \(written.lastPathComponent)")
384                    if open { NSWorkspace.shared.open(written) }
385                } catch {
386                    commands.show("\(error)")
387                }
388            }
389        }
390    }
391
392    /// Work a command hands to the platform: tables recalculated in Emacs.
393    private func runExternal(_ request: ExternalRequest) {
394        switch request {
395        case .openLink(let link):
396            if let message = LinkOpener.open(link, session: session, workspace: workspace) { commands.show(message) }
397        case .editBlock(let edit):
398            blockEdit = BlockEditRequest(edit: edit)
399        case .columnView(let view):
400            panel = .columns(UUID(), view)
401        case .emacsTable(let table, let point, let form, let reason, let lisp):
402            let run = {
403                commands.show("Recalculating in Emacs (\(reason))…")
404                Task { commands.show(await session.recalculateInEmacs(table: table, point: point, form: form)) }
405            }
406            guard lisp, let path = session.path, let text = session.document?.text else { return run() }
407            let content = (text as NSString).substring(with: NSRange(location: table.lowerBound, length: min((text as NSString).length, table.upperBound + 2000) - table.lowerBound))
408            if trust.isTrusted(path: path, content: content) { return run() }
409            commands.ask(Prompt(key: "confirm", message: "This table's formulas run Lisp. Run them? (yes, no, always)", choices: ["yes", "no", "always"])) { answer in
410                switch answer {
411                case "always":
412                    trust.trust(path: path, content: content)
413                    run()
414                case "yes": run()
415                default: commands.show("Not recalculated")
416                }
417            }
418        case .babel(let job):
419            let run = {
420                commands.show("Running \(job.language) block… (⌘. to cancel)")
421                session.startBabel(job) { commands.show($0) }
422            }
423            guard let path = session.path else { return }
424            if !job.alwaysAsk, trust.isTrusted(path: path, content: job.blockText) { return run() }
425            let choices = job.alwaysAsk ? ["yes", "no"] : ["yes", "no", "always"]
426            commands.ask(Prompt(key: "confirm", message: "Run this \(job.language) block? (\(choices.joined(separator: ", ")))", choices: choices)) { answer in
427                switch answer {
428                case "always":
429                    trust.trust(path: path, content: job.blockText)
430                    run()
431                case "yes": run()
432                default: commands.show("Not run")
433                }
434            }
435        }
436    }
437
438    private struct ReminderKey: Hashable {
439        var enabled: Bool
440        var lead: Int
441        var subfolders: Bool
442        var files: Int
443        var changed: Int?
444        var edits: Int
445        var hour: Int
446    }
447
448    /// Sets the notifications for the next week's timed entries, once edits pause.
449    private func updateReminders() async {
450        guard let scheduler else { return }
451        guard remindersEnabled else {
452            await scheduler.clear()
453            return
454        }
455        try? await Task.sleep(for: .seconds(2))
456        guard !Task.isCancelled, !workspace.files.isEmpty else { return }
457        let agenda = reminderAgenda ?? AgendaModel(workspace: workspace)
458        reminderAgenda = agenda
459        agenda.includeSubfolders = agendaSubfolders
460        let open = session.openTexts
461        let reminders = await agenda.reminders(open: open, lead: reminderLead)
462        guard !Task.isCancelled else { return }
463        await scheduler.reconcile(reminders)
464    }
465
466    private func loadKeymap() {
467        let loaded = KeymapLoader.load(preset)
468        keymap = loaded.keymap
469        commands.keymap = loaded.keymap
470        commands.modal = preset.isModal
471        if let first = loaded.problems.first {
472            let more = loaded.problems.count > 1 ? " (and \(loaded.problems.count - 1) more)" : ""
473            commands.show("keymap.toml: \(first)\(more)")
474        }
475    }
476
477    /// `SPC b b`: open buffers, most recent first, by name (with the folder when names repeat).
478    private func switchBuffer() {
479        let paths = session.recentPaths.dropFirst() + session.recentPaths.prefix(1)
480        let names = paths.map { ($0 as NSString).lastPathComponent }
481        let labels = paths.map { path in
482            let name = (path as NSString).lastPathComponent
483            guard names.filter({ $0 == name }).count > 1 else { return name }
484            return name + " — " + ((path as NSString).deletingLastPathComponent as NSString).lastPathComponent
485        }
486        guard !labels.isEmpty else { return commands.show("No buffers are open") }
487        commands.ask(Prompt(key: "buffer", message: "Switch to buffer:", choices: labels)) { answer in
488            guard let answer, let index = labels.firstIndex(of: answer) else { return }
489            session.open(Array(paths)[index])
490        }
491    }
492
493    /// Runs a command from a key, the palette or the Org menu.
494    private func perform(_ id: String) {
495        let orgOnly = ["app.refile", "app.archive", "app.clock.in"].contains(id) || id.hasPrefix("app.export.") || id.hasPrefix("org.")
496        if orgOnly, !session.isOrg {
497            commands.show("Not an org file")
498            return
499        }
500        switch id {
501        case "app.save":
502            if !session.save(), session.conflict != nil { commands.showingConflict = true }
503        case "app.quit": NSApp.terminate(nil)
504        case "app.save-all":
505            if !session.saveAll(), session.conflict != nil { commands.showingConflict = true }
506        case "app.buffer.switch": switchBuffer()
507        case "app.buffer.next": session.cycle(1)
508        case "app.buffer.previous": session.cycle(-1)
509        case "app.buffer.last": session.showPrevious()
510        case "app.buffer.kill":
511            guard let path = session.path else {
512                NSApp.keyWindow?.performClose(nil)
513                return
514            }
515            if UnsavedChanges.resolve(session) { session.kill(path) }
516        case "app.buffer.kill-others":
517            let others = session.openPaths.filter { $0 != session.path }
518            if UnsavedChanges.resolve(session, paths: others) { others.forEach(session.kill) }
519        case "app.buffer.kill-all":
520            let all = session.openPaths
521            if UnsavedChanges.resolve(session, paths: all) { all.forEach(session.kill) }
522        case "app.toggle-tab-bar": showTabBar.toggle()
523        case "app.babel.cancel":
524            if session.isRunningBabel { session.cancelBabel() } else { commands.show("No block is running") }
525        case "app.toggle-outline": toggleOutline()
526        case "app.toggle-markup": showMarkup.toggle()
527        case "app.toggle-line-numbers": showLineNumbers.toggle()
528        case "app.import-emacs": showingImport = true
529        case "app.edit-config": commands.jump(path: UserConfig.configFile.path, offset: 0)
530        case "app.quick-open": commands.showingQuickOpen = true
531        case "app.palette": commands.showingPalette = true
532        case "app.search": commands.focusSearch = true
533        case "app.reload-keymap":
534            loadKeymap()
535            commands.show("Keymap reloaded")
536        case "app.refile":
537            let targets = workspace.refileTargets(openPath: session.path, document: session.document)
538            commands.ask(Prompt(key: "refile", message: "Refile to:", choices: targets.map(\.label))) { answer in
539                guard let answer, let target = targets.first(where: { $0.label == answer }) else { return }
540                if let message = session.refile(to: target) { commands.show(message) }
541            }
542        case "app.archive":
543            if let message = session.archive() { commands.show(message) }
544        case "app.table-import":
545            // `org-table-import`: a TSV, CSV or space-separated file becomes a table at point.
546            guard let editor = commands.editor else { return commands.show("No file is open") }
547            let panel = NSOpenPanel()
548            panel.allowedContentTypes = [.commaSeparatedText, .tabSeparatedText, .plainText]
549            guard panel.runModal() == .OK, let url = panel.url else { return }
550            guard let contents = try? String(contentsOf: url, encoding: .utf8) else { return commands.show("Can't read \(url.lastPathComponent)") }
551            editor.perform(ImportTable(contents: contents))
552        case "app.table-export":
553            // `org-table-export`: CSV for a .csv name, else TSV.
554            guard let editor = commands.editor else { return commands.show("No file is open") }
555            let context = editor.context()
556            guard ImportTable.exportText(context.text, at: context.caret, path: "") != nil else { return commands.show("No table at point") }
557            let panel = NSSavePanel()
558            panel.nameFieldStringValue = "table.csv"
559            guard panel.runModal() == .OK, let url = panel.url,
560                  let text = ImportTable.exportText(context.text, at: context.caret, path: url.path) else { return }
561            do {
562                try text.write(to: url, atomically: true, encoding: .utf8)
563                commands.show("Export done.")
564            } catch {
565                commands.show("File not written: \(error.localizedDescription)")
566            }
567        case "org.subtree.paste":
568            guard let text = NSPasteboard.general.string(forType: .string) else { return commands.show("The clipboard is empty") }
569            commands.editor?.perform(PasteSubtree(text: text))
570        case "org.link.insert":
571            commands.editor?.perform(InsertLink(stored: commands.storedLinks, file: session.path))
572        case "org.link.store":
573            guard let editor = commands.editor, let path = session.path else { return commands.show("No method for storing a link from this buffer") }
574            commands.storeLink(Links.store(in: editor.context(), path: Links.abbreviate(path, home: NSHomeDirectory())))
575        case "org.id.store-link":
576            guard let editor = commands.editor, let path = session.path else { return }
577            if case .commit = editor.perform(CreateID()),
578               let link = Links.storeID(in: editor.context(), fileName: (path as NSString).lastPathComponent) {
579                commands.storeLink(link)
580            }
581        case "app.agenda":
582            openWindow(id: "agenda")
583        case "app.clock.in":
584            commands.show(clock.clockIn(session))
585        case "app.clock.out":
586            commands.show(clock.clockOut(session))
587        case "app.clock.cancel":
588            commands.show(clock.clockOut(session, cancel: true))
589        case "app.clock.goto":
590            if let location = clock.location(session) { commands.jump(path: location.path, offset: location.offset) } else { commands.show("No active clock") }
591        case "app.clock.report":
592            openWindow(id: "clock-report")
593        case "app.board":
594            openWindow(id: "board")
595        case "app.capture":
596            NSApp.activate()
597            openWindow(id: "capture")
598        case "app.export-dialog":
599            guard let path = session.path else { return commands.show("No file is open") }
600            panel = .export(UUID(), URL(fileURLWithPath: path))
601        case let id where id.hasPrefix("app.export."):
602            export(String(id.dropFirst("app.export.".count)))
603        default:
604            if let editor = commands.editor { editor.run(id) } else { commands.show("No file is open") }
605        }
606    }
607
608    private var errorShown: Binding<Bool> {
609        Binding(get: { workspace.lastError != nil || session.lastError != nil }, set: { _ in })
610    }
611}
612
613struct Sidebar: View {
614    let workspace: WorkspaceModel
615    let session: DocumentSession
616    @Binding var selection: String?
617    var addFolder: () -> Void = {}
618    /// Folders shown collapsed, by path, one per line.
619    @AppStorage("collapsedFolders") private var collapsedText = ""
620    @State private var removing: String?
621    /// A file operation waiting for a name or a confirmation.
622    @Environment(\.orgTheme) private var theme
623    @State var pending: FileOperation?
624    @State var name = ""
625    @State var failure: String?
626
627    private var collapsed: Set<String> { Set(collapsedText.split(separator: "\n").map(String.init)) }
628
629    private func expanded(_ root: String) -> Binding<Bool> {
630        Binding {
631            !collapsed.contains(root)
632        } set: { isExpanded in
633            var set = collapsed
634            if isExpanded { set.remove(root) } else { set.insert(root) }
635            collapsedText = set.sorted().joined(separator: "\n")
636        }
637    }
638
639    var body: some View {
640        List(selection: $selection) {
641            ForEach(workspace.rootPaths, id: \.self) { root in
642                Section(isExpanded: expanded(root)) {
643                    OutlineGroup(workspace.tree(forRoot: root).children ?? [], children: \.children) { node in
644                        Label(node.name, systemImage: icon(node))
645                            .foregroundStyle(node.file?.kind == .conflict ? .orange : theme.color("sidebar-foreground") ?? .primary)
646                            .tag(node.file?.path)
647                            .contextMenu { fileMenu(node) }
648                    }
649                } header: {
650                    Text((root as NSString).lastPathComponent)
651                        .foregroundStyle(theme.color("sidebar-header") ?? .secondary)
652                        .help(root)
653                        .contextMenu { folderMenu(root) }
654                }
655            }
656        }
657        .listStyle(.sidebar)
658        .themedListBackground(theme.color("sidebar-background"))
659        .safeAreaInset(edge: .bottom, spacing: 0) {
660            HStack(spacing: 4) {
661                Button("Add Folder…", systemImage: "plus", action: addFolder)
662                    .help("Add a folder (⇧⌘O)")
663                Menu {
664                    ForEach(workspace.rootPaths, id: \.self) { root in
665                        Button((root as NSString).lastPathComponent) { removing = root }
666                    }
667                } label: {
668                    Label("Remove Folder", systemImage: "minus")
669                }
670                .menuIndicator(.hidden)
671                .fixedSize()
672                .disabled(workspace.rootPaths.isEmpty)
673                .help("Remove a folder from the sidebar")
674                Spacer()
675            }
676            .labelStyle(.iconOnly)
677            .buttonStyle(.borderless)
678            .menuStyle(.borderlessButton)
679            .padding(.horizontal, 10)
680            .padding(.vertical, 6)
681        }
682        .confirmationDialog(
683            "Remove “\(removing.map { ($0 as NSString).lastPathComponent } ?? "")” from the sidebar?",
684            isPresented: Binding { removing != nil } set: { if !$0 { removing = nil } }
685        ) {
686            Button("Remove") {
687                if let root = removing { try? workspace.removeRoot(path: root) }
688                removing = nil
689            }
690        } message: {
691            Text("The folder and its files stay on disk.")
692        }
693        .fileOperations(self)
694    }
695
696    @ViewBuilder
697    private func folderMenu(_ root: String) -> some View {
698        Button("New File…") { ask(.create(folder: root)) }
699        Divider()
700        Button(collapsed.contains(root) ? "Expand" : "Collapse") { expanded(root).wrappedValue.toggle() }
701        Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: root)]) }
702        Divider()
703        Button("Remove from Sidebar…") { removing = root }
704    }
705
706    private func icon(_ node: FileTreeNode) -> String {
707        guard let file = node.file else { return "folder" }
708        switch file.kind {
709        case .org: return "doc.text"
710        case .archive: return "archivebox"
711        case .conflict: return "exclamationmark.triangle"
712        case .other:
713            guard let type = UTType(filenameExtension: (file.path as NSString).pathExtension) else { return "doc" }
714            if type.conforms(to: .image) { return "photo" }
715            if type.conforms(to: .pdf) { return "doc.richtext" }
716            if type.conforms(to: .audiovisualContent) { return "play.rectangle" }
717            if type.conforms(to: .sourceCode) || type.conforms(to: .script) { return "chevron.left.forwardslash.chevron.right" }
718            if type.conforms(to: .text) { return "doc.plaintext" }
719            return "doc"
720        }
721    }
722}
723
724struct OutlineColumn: View {
725    let session: DocumentSession
726    @Environment(\.orgTheme) private var theme
727
728    var body: some View {
729        List(Array(session.outline.enumerated()), id: \.element.start) { _, entry in
730            Button {
731                session.reveal(entry.start)
732            } label: {
733                Text(entry.title.isEmpty ? "(untitled)" : entry.title)
734                    .foregroundStyle(theme.color("sidebar-foreground") ?? .primary)
735                    .lineLimit(1)
736                    .padding(.leading, CGFloat(entry.level - 1) * 12)
737            }
738            .buttonStyle(.plain)
739        }
740        .themedListBackground(theme.color("sidebar-background"))
741        .overlay {
742            if session.path != nil, !session.isOrg {
743                ContentUnavailableView("No outline", systemImage: "doc.plaintext", description: Text("Only org files have an outline."))
744            } else if session.path != nil, session.outline.isEmpty {
745                ContentUnavailableView("No headings", systemImage: "list.bullet.indent")
746            }
747        }
748    }
749}
750
751struct SearchResults: View {
752    let results: [HeadingLocation]
753    let open: (HeadingLocation) -> Void
754
755    var body: some View {
756        List(results, id: \.self) { location in
757            Button {
758                open(location)
759            } label: {
760                VStack(alignment: .leading, spacing: 2) {
761                    Text(location.title.isEmpty ? "(untitled)" : location.title).lineLimit(1)
762                    Text((location.path as NSString).lastPathComponent).font(.caption).foregroundStyle(.secondary)
763                }
764            }
765            .buttonStyle(.plain)
766        }
767        .overlay {
768            if results.isEmpty { ContentUnavailableView.search }
769        }
770    }
771}
772
773struct QuickOpenView: View {
774    let workspace: WorkspaceModel
775    let open: (FileEntry) -> Void
776    @State private var query = ""
777    @Environment(\.dismiss) private var dismiss
778
779    var body: some View {
780        let matches = workspace.quickOpen(query)
781        VStack(spacing: 0) {
782            TextField("Open file", text: $query)
783                .textFieldStyle(.plain)
784                .font(.title3)
785                .padding(12)
786                .onSubmit { if let first = matches.first { open(first) } }
787            Divider()
788            List(matches) { entry in
789                Button {
790                    open(entry)
791                } label: {
792                    VStack(alignment: .leading, spacing: 2) {
793                        Text(entry.name)
794                        Text(entry.relativePath).font(.caption).foregroundStyle(.secondary)
795                    }
796                }
797                .buttonStyle(.plain)
798            }
799        }
800        .frame(width: 520, height: 360)
801        .onExitCommand { dismiss() }
802    }
803}
804
805/// A divider that resizes the pane before it by dragging. An `HSplitView` inside the window's
806/// split view loops on its size constraints in short windows, so this sets a width instead.
807struct PaneDivider: View {
808    @Binding var width: Double
809    let range: ClosedRange<Double>
810    @State private var start: Double?
811
812    var body: some View {
813        Rectangle()
814            .fill(Color(nsColor: .separatorColor))
815            .frame(width: 1)
816            .frame(maxHeight: .infinity)
817            .overlay(Color.clear.frame(width: 7).contentShape(Rectangle()).onHover { inside in
818                if inside { NSCursor.resizeLeftRight.push() } else { NSCursor.pop() }
819            }
820            .gesture(DragGesture(minimumDistance: 1).onChanged { drag in
821                let base = start ?? width
822                start = base
823                width = min(max(base + drag.translation.width, range.lowerBound), range.upperBound)
824            }.onEnded { _ in start = nil }))
825            .accessibilityHidden(true)
826    }
827}
828
829/// A tab for each open buffer: click to show it, × to close it, a dot for unsaved edits.
830struct BufferTabs: View {
831    let session: DocumentSession
832    @Environment(\.orgTheme) private var theme
833
834    var body: some View {
835        ScrollView(.horizontal, showsIndicators: false) {
836            HStack(spacing: 0) {
837                ForEach(session.openPaths, id: \.self) { path in
838                    tab(path)
839                }
840            }
841        }
842        .frame(height: 28)
843        .background { Rectangle().fill(theme.color("modeline-background").map(AnyShapeStyle.init) ?? AnyShapeStyle(.bar)) }
844        .overlay(alignment: .bottom) { Divider() }
845    }
846
847    private func tab(_ path: String) -> some View {
848        let current = path == session.path
849        return HStack(spacing: 6) {
850            Text((path as NSString).lastPathComponent)
851                .lineLimit(1)
852                .foregroundStyle(current ? .primary : .secondary)
853            Button {
854                if path == session.path {
855                    if UnsavedChanges.resolve(session) { session.kill(path) }
856                } else if UnsavedChanges.resolve(session, paths: [path]) {
857                    session.kill(path)
858                }
859            } label: {
860                Image(systemName: session.dirtyPaths.contains(path) ? "circle.fill" : "xmark")
861                    .font(.system(size: session.dirtyPaths.contains(path) ? 6 : 9, weight: .semibold))
862                    .frame(width: 12, height: 12)
863            }
864            .buttonStyle(.borderless)
865            .help("Close")
866        }
867        .font(.callout)
868        .padding(.horizontal, 12)
869        .frame(maxHeight: .infinity)
870        // A shape, not a color: a color background runs up under the toolbar.
871        .background { Rectangle().fill(current ? theme.color("background") ?? Color(nsColor: .textBackgroundColor) : .clear) }
872        .overlay(alignment: .trailing) { Divider() }
873        .contentShape(Rectangle())
874        .onTapGesture { session.open(path) }
875        .help(path)
876    }
877}
878
879enum Panel: Identifiable {
880    case columns(UUID, ColumnView.View)
881    case export(UUID, URL)
882
883    var id: UUID {
884        switch self {
885        case .columns(let id, _), .export(let id, _): id
886        }
887    }
888}
889
890struct BlockEditRequest: Identifiable {
891    let id = UUID()
892    let edit: BlockEdit
893}