Sources/Orgstar/ContentView.swift

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

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