Sources/Orgstar/ContentView.swift

30f6716c5b85f009c8cee977f3e5e4e4b5df3d09
orgstar/Sources/Orgstar/ContentView.swift history · blame · raw

919 lines · 43639 bytes

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