Sources/Orgstar/ContentView.swift

a9ec94b75caa22bf47461bc180158d2b961bc747
orgstar/Sources/Orgstar/ContentView.swift

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