Sources/Orgstar/ContentView.swift

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