Sources/Orgstar/ContentView.swift

25a6d84c1f41024c27ce1de5be1d3bf6425f76d0
orgstar/Sources/Orgstar/ContentView.swift history · blame · raw

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