Sources/Orgstar/ContentView.swift

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

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