Sources/Orgstar/ContentView.swift

4b4dc0135e1d59d493a0a49865fcd155aeea59e0
orgstar/Sources/Orgstar/ContentView.swift history · blame · raw

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