Sources/Orgstar/ContentView.swift

b7b7f8ef81367a5e787840c1b28d8a82bf7da545
orgstar/Sources/Orgstar/ContentView.swift history · blame · raw

848 lines · 39741 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            }
318            if let id = DevelopmentHooks.windowToOpen {
319                if id == "settings" { openSettings() } else { openWindow(id: id) }
320            }
321            await workspace.refresh()
322            workspace.startWatching()
323        }
324    }
325
326    /// Writes the export beside the file, as Emacs's export dispatcher does.
327    private func export(_ format: String) {
328        guard let path = session.path, let text = session.document?.text else {
329            commands.show("No file is open")
330            return
331        }
332        let url = URL(fileURLWithPath: path)
333        let base = url.deletingPathExtension()
334        let defaults = Preferences.orgSettings
335        switch format {
336        case "html", "html-open", "markdown":
337            let target = base.appendingPathExtension(format == "markdown" ? "md" : "html")
338            let content = format == "markdown"
339                ? MarkdownExport.document(text, settings: defaults)
340                : HTMLExport.page(text, fallbackTitle: base.lastPathComponent, settings: defaults)
341            do {
342                try content.write(to: target, atomically: true, encoding: .utf8)
343                commands.show("Exported to \(target.lastPathComponent)")
344                if format == "html-open" { NSWorkspace.shared.open(target) }
345            } catch {
346                commands.show("Can't write \(target.lastPathComponent): \(error.localizedDescription)")
347            }
348        default:
349            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"]
350            guard let function = functions[format] else { return }
351            commands.show("Exporting with Emacs…")
352            Task {
353                do {
354                    let written = try await EmacsRunner.export(text: text, path: path, function: function)
355                    commands.show("Exported to \((written as NSString).lastPathComponent)")
356                } catch {
357                    commands.show("\(error)")
358                }
359            }
360        }
361    }
362
363    /// Work a command hands to the platform: tables recalculated in Emacs.
364    private func runExternal(_ request: ExternalRequest) {
365        switch request {
366        case .openLink(let link):
367            if let message = LinkOpener.open(link, session: session, workspace: workspace) { commands.show(message) }
368        case .editBlock(let edit):
369            blockEdit = BlockEditRequest(edit: edit)
370        case .emacsTable(let table, let point, let form, let reason, let lisp):
371            let run = {
372                commands.show("Recalculating in Emacs (\(reason))…")
373                Task { commands.show(await session.recalculateInEmacs(table: table, point: point, form: form)) }
374            }
375            guard lisp, let path = session.path, let text = session.document?.text else { return run() }
376            let content = (text as NSString).substring(with: NSRange(location: table.lowerBound, length: min((text as NSString).length, table.upperBound + 2000) - table.lowerBound))
377            if trust.isTrusted(path: path, content: content) { return run() }
378            commands.ask(Prompt(key: "confirm", message: "This table's formulas run Lisp. Run them? (yes, no, always)", choices: ["yes", "no", "always"])) { answer in
379                switch answer {
380                case "always":
381                    trust.trust(path: path, content: content)
382                    run()
383                case "yes": run()
384                default: commands.show("Not recalculated")
385                }
386            }
387        case .babel(let job):
388            let run = {
389                commands.show("Running \(job.language) block… (⌘. to cancel)")
390                session.startBabel(job) { commands.show($0) }
391            }
392            guard let path = session.path else { return }
393            if !job.alwaysAsk, trust.isTrusted(path: path, content: job.blockText) { return run() }
394            let choices = job.alwaysAsk ? ["yes", "no"] : ["yes", "no", "always"]
395            commands.ask(Prompt(key: "confirm", message: "Run this \(job.language) block? (\(choices.joined(separator: ", ")))", choices: choices)) { answer in
396                switch answer {
397                case "always":
398                    trust.trust(path: path, content: job.blockText)
399                    run()
400                case "yes": run()
401                default: commands.show("Not run")
402                }
403            }
404        }
405    }
406
407    private struct ReminderKey: Hashable {
408        var enabled: Bool
409        var lead: Int
410        var subfolders: Bool
411        var files: Int
412        var changed: Int?
413        var edits: Int
414        var hour: Int
415    }
416
417    /// Sets the notifications for the next week's timed entries, once edits pause.
418    private func updateReminders() async {
419        guard let scheduler else { return }
420        guard remindersEnabled else {
421            await scheduler.clear()
422            return
423        }
424        try? await Task.sleep(for: .seconds(2))
425        guard !Task.isCancelled, !workspace.files.isEmpty else { return }
426        let agenda = reminderAgenda ?? AgendaModel(workspace: workspace)
427        reminderAgenda = agenda
428        agenda.includeSubfolders = agendaSubfolders
429        let open = session.openTexts
430        let reminders = await agenda.reminders(open: open, lead: reminderLead)
431        guard !Task.isCancelled else { return }
432        await scheduler.reconcile(reminders)
433    }
434
435    private func loadKeymap() {
436        let loaded = KeymapLoader.load(preset)
437        keymap = loaded.keymap
438        commands.keymap = loaded.keymap
439        commands.modal = preset.isModal
440        if let first = loaded.problems.first {
441            let more = loaded.problems.count > 1 ? " (and \(loaded.problems.count - 1) more)" : ""
442            commands.show("keymap.toml: \(first)\(more)")
443        }
444    }
445
446    /// `SPC b b`: open buffers, most recent first, by name (with the folder when names repeat).
447    private func switchBuffer() {
448        let paths = session.recentPaths.dropFirst() + session.recentPaths.prefix(1)
449        let names = paths.map { ($0 as NSString).lastPathComponent }
450        let labels = paths.map { path in
451            let name = (path as NSString).lastPathComponent
452            guard names.filter({ $0 == name }).count > 1 else { return name }
453            return name + " — " + ((path as NSString).deletingLastPathComponent as NSString).lastPathComponent
454        }
455        guard !labels.isEmpty else { return commands.show("No buffers are open") }
456        commands.ask(Prompt(key: "buffer", message: "Switch to buffer:", choices: labels)) { answer in
457            guard let answer, let index = labels.firstIndex(of: answer) else { return }
458            session.open(Array(paths)[index])
459        }
460    }
461
462    /// Runs a command from a key, the palette or the Org menu.
463    private func perform(_ id: String) {
464        let orgOnly = ["app.refile", "app.archive", "app.clock.in"].contains(id) || id.hasPrefix("app.export.") || id.hasPrefix("org.")
465        if orgOnly, !session.isOrg {
466            commands.show("Not an org file")
467            return
468        }
469        switch id {
470        case "app.save":
471            if !session.save(), session.conflict != nil { commands.showingConflict = true }
472        case "app.quit": NSApp.terminate(nil)
473        case "app.save-all":
474            if !session.saveAll(), session.conflict != nil { commands.showingConflict = true }
475        case "app.buffer.switch": switchBuffer()
476        case "app.buffer.next": session.cycle(1)
477        case "app.buffer.previous": session.cycle(-1)
478        case "app.buffer.last": session.showPrevious()
479        case "app.buffer.kill":
480            guard let path = session.path else {
481                NSApp.keyWindow?.performClose(nil)
482                return
483            }
484            if UnsavedChanges.resolve(session) { session.kill(path) }
485        case "app.buffer.kill-others":
486            let others = session.openPaths.filter { $0 != session.path }
487            if UnsavedChanges.resolve(session, paths: others) { others.forEach(session.kill) }
488        case "app.buffer.kill-all":
489            let all = session.openPaths
490            if UnsavedChanges.resolve(session, paths: all) { all.forEach(session.kill) }
491        case "app.toggle-tab-bar": showTabBar.toggle()
492        case "app.babel.cancel":
493            if session.isRunningBabel { session.cancelBabel() } else { commands.show("No block is running") }
494        case "app.toggle-outline": toggleOutline()
495        case "app.toggle-markup": showMarkup.toggle()
496        case "app.toggle-line-numbers": showLineNumbers.toggle()
497        case "app.import-emacs": showingImport = true
498        case "app.edit-config": commands.jump(path: UserConfig.configFile.path, offset: 0)
499        case "app.quick-open": commands.showingQuickOpen = true
500        case "app.palette": commands.showingPalette = true
501        case "app.search": commands.focusSearch = true
502        case "app.reload-keymap":
503            loadKeymap()
504            commands.show("Keymap reloaded")
505        case "app.refile":
506            let targets = workspace.refileTargets(openPath: session.path, document: session.document)
507            commands.ask(Prompt(key: "refile", message: "Refile to:", choices: targets.map(\.label))) { answer in
508                guard let answer, let target = targets.first(where: { $0.label == answer }) else { return }
509                if let message = session.refile(to: target) { commands.show(message) }
510            }
511        case "app.archive":
512            if let message = session.archive() { commands.show(message) }
513        case "app.table-import":
514            // `org-table-import`: a TSV, CSV or space-separated file becomes a table at point.
515            guard let editor = commands.editor else { return commands.show("No file is open") }
516            let panel = NSOpenPanel()
517            panel.allowedContentTypes = [.commaSeparatedText, .tabSeparatedText, .plainText]
518            guard panel.runModal() == .OK, let url = panel.url else { return }
519            guard let contents = try? String(contentsOf: url, encoding: .utf8) else { return commands.show("Can't read \(url.lastPathComponent)") }
520            editor.perform(ImportTable(contents: contents))
521        case "app.table-export":
522            // `org-table-export`: CSV for a .csv name, else TSV.
523            guard let editor = commands.editor else { return commands.show("No file is open") }
524            let context = editor.context()
525            guard ImportTable.exportText(context.text, at: context.caret, path: "") != nil else { return commands.show("No table at point") }
526            let panel = NSSavePanel()
527            panel.nameFieldStringValue = "table.csv"
528            guard panel.runModal() == .OK, let url = panel.url,
529                  let text = ImportTable.exportText(context.text, at: context.caret, path: url.path) else { return }
530            do {
531                try text.write(to: url, atomically: true, encoding: .utf8)
532                commands.show("Export done.")
533            } catch {
534                commands.show("File not written: \(error.localizedDescription)")
535            }
536        case "org.subtree.paste":
537            guard let text = NSPasteboard.general.string(forType: .string) else { return commands.show("The clipboard is empty") }
538            commands.editor?.perform(PasteSubtree(text: text))
539        case "org.link.insert":
540            commands.editor?.perform(InsertLink(stored: commands.storedLinks, file: session.path))
541        case "org.link.store":
542            guard let editor = commands.editor, let path = session.path else { return commands.show("No method for storing a link from this buffer") }
543            commands.storeLink(Links.store(in: editor.context(), path: Links.abbreviate(path, home: NSHomeDirectory())))
544        case "org.id.store-link":
545            guard let editor = commands.editor, let path = session.path else { return }
546            if case .commit = editor.perform(CreateID()),
547               let link = Links.storeID(in: editor.context(), fileName: (path as NSString).lastPathComponent) {
548                commands.storeLink(link)
549            }
550        case "app.agenda":
551            openWindow(id: "agenda")
552        case "app.clock.in":
553            commands.show(clock.clockIn(session))
554        case "app.clock.out":
555            commands.show(clock.clockOut(session))
556        case "app.clock.cancel":
557            commands.show(clock.clockOut(session, cancel: true))
558        case "app.clock.goto":
559            if let location = clock.location(session) { commands.jump(path: location.path, offset: location.offset) } else { commands.show("No active clock") }
560        case "app.clock.report":
561            openWindow(id: "clock-report")
562        case "app.board":
563            openWindow(id: "board")
564        case "app.capture":
565            NSApp.activate()
566            openWindow(id: "capture")
567        case let id where id.hasPrefix("app.export."):
568            export(String(id.dropFirst("app.export.".count)))
569        default:
570            if let editor = commands.editor { editor.run(id) } else { commands.show("No file is open") }
571        }
572    }
573
574    private var errorShown: Binding<Bool> {
575        Binding(get: { workspace.lastError != nil || session.lastError != nil }, set: { _ in })
576    }
577}
578
579struct Sidebar: View {
580    let workspace: WorkspaceModel
581    let session: DocumentSession
582    @Binding var selection: String?
583    var addFolder: () -> Void = {}
584    /// Folders shown collapsed, by path, one per line.
585    @AppStorage("collapsedFolders") private var collapsedText = ""
586    @State private var removing: String?
587    /// A file operation waiting for a name or a confirmation.
588    @Environment(\.orgTheme) private var theme
589    @State var pending: FileOperation?
590    @State var name = ""
591    @State var failure: String?
592
593    private var collapsed: Set<String> { Set(collapsedText.split(separator: "\n").map(String.init)) }
594
595    private func expanded(_ root: String) -> Binding<Bool> {
596        Binding {
597            !collapsed.contains(root)
598        } set: { isExpanded in
599            var set = collapsed
600            if isExpanded { set.remove(root) } else { set.insert(root) }
601            collapsedText = set.sorted().joined(separator: "\n")
602        }
603    }
604
605    var body: some View {
606        List(selection: $selection) {
607            ForEach(workspace.rootPaths, id: \.self) { root in
608                Section(isExpanded: expanded(root)) {
609                    OutlineGroup(workspace.tree(forRoot: root).children ?? [], children: \.children) { node in
610                        Label(node.name, systemImage: icon(node))
611                            .foregroundStyle(node.file?.kind == .conflict ? .orange : theme.color("sidebar-foreground") ?? .primary)
612                            .tag(node.file?.path)
613                            .contextMenu { fileMenu(node) }
614                    }
615                } header: {
616                    Text((root as NSString).lastPathComponent)
617                        .foregroundStyle(theme.color("sidebar-header") ?? .secondary)
618                        .help(root)
619                        .contextMenu { folderMenu(root) }
620                }
621            }
622        }
623        .listStyle(.sidebar)
624        .themedListBackground(theme.color("sidebar-background"))
625        .safeAreaInset(edge: .bottom, spacing: 0) {
626            HStack(spacing: 4) {
627                Button("Add Folder…", systemImage: "plus", action: addFolder)
628                    .help("Add a folder (⇧⌘O)")
629                Menu {
630                    ForEach(workspace.rootPaths, id: \.self) { root in
631                        Button((root as NSString).lastPathComponent) { removing = root }
632                    }
633                } label: {
634                    Label("Remove Folder", systemImage: "minus")
635                }
636                .menuIndicator(.hidden)
637                .fixedSize()
638                .disabled(workspace.rootPaths.isEmpty)
639                .help("Remove a folder from the sidebar")
640                Spacer()
641            }
642            .labelStyle(.iconOnly)
643            .buttonStyle(.borderless)
644            .menuStyle(.borderlessButton)
645            .padding(.horizontal, 10)
646            .padding(.vertical, 6)
647        }
648        .confirmationDialog(
649            "Remove “\(removing.map { ($0 as NSString).lastPathComponent } ?? "")” from the sidebar?",
650            isPresented: Binding { removing != nil } set: { if !$0 { removing = nil } }
651        ) {
652            Button("Remove") {
653                if let root = removing { try? workspace.removeRoot(path: root) }
654                removing = nil
655            }
656        } message: {
657            Text("The folder and its files stay on disk.")
658        }
659        .fileOperations(self)
660    }
661
662    @ViewBuilder
663    private func folderMenu(_ root: String) -> some View {
664        Button("New File…") { ask(.create(folder: root)) }
665        Divider()
666        Button(collapsed.contains(root) ? "Expand" : "Collapse") { expanded(root).wrappedValue.toggle() }
667        Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: root)]) }
668        Divider()
669        Button("Remove from Sidebar…") { removing = root }
670    }
671
672    private func icon(_ node: FileTreeNode) -> String {
673        guard let file = node.file else { return "folder" }
674        switch file.kind {
675        case .org: return "doc.text"
676        case .archive: return "archivebox"
677        case .conflict: return "exclamationmark.triangle"
678        case .other:
679            guard let type = UTType(filenameExtension: (file.path as NSString).pathExtension) else { return "doc" }
680            if type.conforms(to: .image) { return "photo" }
681            if type.conforms(to: .pdf) { return "doc.richtext" }
682            if type.conforms(to: .audiovisualContent) { return "play.rectangle" }
683            if type.conforms(to: .sourceCode) || type.conforms(to: .script) { return "chevron.left.forwardslash.chevron.right" }
684            if type.conforms(to: .text) { return "doc.plaintext" }
685            return "doc"
686        }
687    }
688}
689
690struct OutlineColumn: View {
691    let session: DocumentSession
692    @Environment(\.orgTheme) private var theme
693
694    var body: some View {
695        List(Array(session.outline.enumerated()), id: \.element.start) { _, entry in
696            Button {
697                session.reveal(entry.start)
698            } label: {
699                Text(entry.title.isEmpty ? "(untitled)" : entry.title)
700                    .foregroundStyle(theme.color("sidebar-foreground") ?? .primary)
701                    .lineLimit(1)
702                    .padding(.leading, CGFloat(entry.level - 1) * 12)
703            }
704            .buttonStyle(.plain)
705        }
706        .themedListBackground(theme.color("sidebar-background"))
707        .overlay {
708            if session.path != nil, !session.isOrg {
709                ContentUnavailableView("No outline", systemImage: "doc.plaintext", description: Text("Only org files have an outline."))
710            } else if session.path != nil, session.outline.isEmpty {
711                ContentUnavailableView("No headings", systemImage: "list.bullet.indent")
712            }
713        }
714    }
715}
716
717struct SearchResults: View {
718    let results: [HeadingLocation]
719    let open: (HeadingLocation) -> Void
720
721    var body: some View {
722        List(results, id: \.self) { location in
723            Button {
724                open(location)
725            } label: {
726                VStack(alignment: .leading, spacing: 2) {
727                    Text(location.title.isEmpty ? "(untitled)" : location.title).lineLimit(1)
728                    Text((location.path as NSString).lastPathComponent).font(.caption).foregroundStyle(.secondary)
729                }
730            }
731            .buttonStyle(.plain)
732        }
733        .overlay {
734            if results.isEmpty { ContentUnavailableView.search }
735        }
736    }
737}
738
739struct QuickOpenView: View {
740    let workspace: WorkspaceModel
741    let open: (FileEntry) -> Void
742    @State private var query = ""
743    @Environment(\.dismiss) private var dismiss
744
745    var body: some View {
746        let matches = workspace.quickOpen(query)
747        VStack(spacing: 0) {
748            TextField("Open file", text: $query)
749                .textFieldStyle(.plain)
750                .font(.title3)
751                .padding(12)
752                .onSubmit { if let first = matches.first { open(first) } }
753            Divider()
754            List(matches) { entry in
755                Button {
756                    open(entry)
757                } label: {
758                    VStack(alignment: .leading, spacing: 2) {
759                        Text(entry.name)
760                        Text(entry.relativePath).font(.caption).foregroundStyle(.secondary)
761                    }
762                }
763                .buttonStyle(.plain)
764            }
765        }
766        .frame(width: 520, height: 360)
767        .onExitCommand { dismiss() }
768    }
769}
770
771/// A divider that resizes the pane before it by dragging. An `HSplitView` inside the window's
772/// split view loops on its size constraints in short windows, so this sets a width instead.
773struct PaneDivider: View {
774    @Binding var width: Double
775    let range: ClosedRange<Double>
776    @State private var start: Double?
777
778    var body: some View {
779        Rectangle()
780            .fill(Color(nsColor: .separatorColor))
781            .frame(width: 1)
782            .frame(maxHeight: .infinity)
783            .overlay(Color.clear.frame(width: 7).contentShape(Rectangle()).onHover { inside in
784                if inside { NSCursor.resizeLeftRight.push() } else { NSCursor.pop() }
785            }
786            .gesture(DragGesture(minimumDistance: 1).onChanged { drag in
787                let base = start ?? width
788                start = base
789                width = min(max(base + drag.translation.width, range.lowerBound), range.upperBound)
790            }.onEnded { _ in start = nil }))
791            .accessibilityHidden(true)
792    }
793}
794
795/// A tab for each open buffer: click to show it, × to close it, a dot for unsaved edits.
796struct BufferTabs: View {
797    let session: DocumentSession
798    @Environment(\.orgTheme) private var theme
799
800    var body: some View {
801        ScrollView(.horizontal, showsIndicators: false) {
802            HStack(spacing: 0) {
803                ForEach(session.openPaths, id: \.self) { path in
804                    tab(path)
805                }
806            }
807        }
808        .frame(height: 28)
809        .background { Rectangle().fill(theme.color("modeline-background").map(AnyShapeStyle.init) ?? AnyShapeStyle(.bar)) }
810        .overlay(alignment: .bottom) { Divider() }
811    }
812
813    private func tab(_ path: String) -> some View {
814        let current = path == session.path
815        return HStack(spacing: 6) {
816            Text((path as NSString).lastPathComponent)
817                .lineLimit(1)
818                .foregroundStyle(current ? .primary : .secondary)
819            Button {
820                if path == session.path {
821                    if UnsavedChanges.resolve(session) { session.kill(path) }
822                } else if UnsavedChanges.resolve(session, paths: [path]) {
823                    session.kill(path)
824                }
825            } label: {
826                Image(systemName: session.dirtyPaths.contains(path) ? "circle.fill" : "xmark")
827                    .font(.system(size: session.dirtyPaths.contains(path) ? 6 : 9, weight: .semibold))
828                    .frame(width: 12, height: 12)
829            }
830            .buttonStyle(.borderless)
831            .help("Close")
832        }
833        .font(.callout)
834        .padding(.horizontal, 12)
835        .frame(maxHeight: .infinity)
836        // A shape, not a color: a color background runs up under the toolbar.
837        .background { Rectangle().fill(current ? theme.color("background") ?? Color(nsColor: .textBackgroundColor) : .clear) }
838        .overlay(alignment: .trailing) { Divider() }
839        .contentShape(Rectangle())
840        .onTapGesture { session.open(path) }
841        .help(path)
842    }
843}
844
845struct BlockEditRequest: Identifiable {
846    let id = UUID()
847    let edit: BlockEdit
848}