krz/orgstar

A native macOS editor for org-mode files. editor org-mode swift

Sources/Orgstar/ContentView.swift

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

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