Sources/Orgstar/ContentView.swift

6a36ba0352b0f5419d22dd2e4100ecf4f38b8ea7
orgstar/Sources/Orgstar/ContentView.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form