Sources/Orgstar/ContentView.swift

2cef47f82373d81f99d371b9aceb8bdc702f54c1
orgstar/Sources/Orgstar/ContentView.swift history · blame · raw

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