Sources/Orgstar/ContentView.swift

d4c76b8503d7069cc3c2404db3cafc46defe1a9a
orgstar/Sources/Orgstar/ContentView.swift history · blame · raw

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