Sources/Orgstar/ContentView.swift

1569d791fbc3c0618d100bc101222d3bfc5f56d9
orgstar/Sources/Orgstar/ContentView.swift history · blame · raw

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