Sources/Orgstar/ContentView.swift

71333253c9544b857c22f69f56d3af166b7ef573
orgstar/Sources/Orgstar/ContentView.swift history · blame · raw

909 lines · 42964 bytes

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