Sources/Orgstar/ContentView.swift

3f183dc5a69542840ae20a73ec755d1148b354dd
orgstar/Sources/Orgstar/ContentView.swift history · blame · raw

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