Sources/Orgstar/OrgstarApp.swift

f24016fbc9384e5bae26abb48db212a9330b488b
orgstar/Sources/Orgstar/OrgstarApp.swift

1289 lines · 62424 bytes

   1import AppKit
   2import OrgApp
   3import OrgCore
   4import OrgEditorAppKit
   5import OrgIndex
   6import OrgMathJax
   7import OrgPresentation
   8#if !APPSTORE
   9import OrgPrograms
  10#endif
  11import SwiftUI
  12import UserNotifications
  13
  14/// Window-level requests the menu bar makes.
  15@MainActor
  16@Observable
  17final class AppCommands {
  18    var showingQuickOpen = false
  19    var showingFolderPicker = false
  20    /// The first-launch sheet, while no folder has been added.
  21    var showingWelcome = false
  22    /// The notes the main window shows as a sheet.
  23    var whatsNew: ReleaseNotes?
  24    var focusSearch = false
  25    var showingConflict = false
  26    var showingPalette = false
  27    var showingMessages = false
  28    /// The main window's outline pane is shown, for View ▸ Show Outline.
  29    var outlineShown = false
  30    /// A location another window asked the main window to show.
  31    private(set) var jumpRequest: (path: String, offset: Int, id: Int)?
  32    private var jumpID = 0
  33    /// Days the agenda window should show, from a followed timestamp.
  34    var agendaRequest: (start: Int, days: Int)?
  35    /// The editor with focus, for menus and the palette.
  36    var editor: OrgEditor?
  37    /// The editors and text views of every pane in every window.
  38    let store = EditorStore()
  39    /// The main window is on screen. App commands run there, so an editor window reopens it
  40    /// before asking for one.
  41    var mainWindowOpen = false
  42    /// What every editor is set up with, from the settings; the main window keeps it current.
  43    var editorSettings = EditorSettings()
  44    /// Runs work outside the text (a table recalculation in Emacs); the main window sets it.
  45    var externalHandler: ((ExternalRequest) -> Void)?
  46    /// Files and images pasted or dropped on an editor; the main window sets them.
  47    var filesHandler: (([URL]) -> Void)?
  48    var imageHandler: ((Data, String) -> Void)?
  49    #if APPSTORE
  50    /// Asks for the folders outside the sidebar's folders that paths need; the main window sets it.
  51    var reach: ([String]) -> Bool = { _ in true }
  52    #endif
  53    /// Tags used across the workspace, for tag completion; the main window sets it.
  54    var knownTags: () -> [String] = { [] }
  55    /// The index completion asks for headings, values and words; the main window sets it.
  56    var completionIndex: IndexStore?
  57    /// The pending key prefix, and what can follow it.
  58    var pendingKeys: String?
  59    /// The editor's evil state in the Doom preset.
  60    var editorState: String?
  61    /// The keymap in use, for showing keys in menus and the palette.
  62    var keymap = KeymapPreset.emacs.keymap
  63    var modal = false
  64    /// `org-stored-links`, most recent first; kept for the session, as in Emacs.
  65    var storedLinks: [StoredLink] = []
  66
  67    /// Puts `link` first in `storedLinks` and says what happened.
  68    func storeLink(_ link: StoredLink) {
  69        show(StoredLink.add(link, to: &storedLinks))
  70    }
  71
  72    /// The keys that run `command`, as menus and the palette show them.
  73    func keyLabel(for command: String) -> String? {
  74        let labels = keymap.keyLabels(for: command, modes: modal ? ["normal", "insert"] : [nil])
  75        return labels.isEmpty ? nil : labels.joined(separator: ", ")
  76    }
  77
  78    /// The editor's selection, for the modeline.
  79    var selection = NSRange(location: 0, length: 0)
  80    var keyHints: [KeyHint] = []
  81    /// A question a command asked, answered in the echo area.
  82    private(set) var prompt: PromptRequest?
  83    /// The last message from a command or the keymap, kept until the next key or click, as
  84    /// Emacs keeps it.
  85    private(set) var message: String?
  86    /// Recent messages, oldest first, for Messages.
  87    private(set) var messages: [String] = []
  88    @ObservationIgnored private var inputMonitor: Any?
  89
  90    func ask(_ prompt: Prompt, reply: @escaping (String?) -> Void) {
  91        self.prompt = PromptRequest(prompt: prompt, reply: reply)
  92    }
  93
  94    /// Clock questions in the echo area.
  95    var askClock: ClockModel.Ask {
  96        { [self] prompt in
  97            await withCheckedContinuation { continuation in
  98                ask(prompt) { continuation.resume(returning: $0) }
  99            }
 100        }
 101    }
 102
 103    /// Ends the prompt with an answer, or nil to cancel, and gives the editor the keys back.
 104    func answer(_ text: String?) {
 105        guard let request = prompt else { return }
 106        prompt = nil
 107        if let textView = editor?.textView { textView.window?.makeFirstResponder(textView) }
 108        request.reply(text)
 109    }
 110
 111    /// An export or table recalculation running in Emacs, for Cancel Running Task.
 112    private(set) var emacsTask: Task<Void, Never>?
 113    private var emacsSerial = 0
 114
 115    /// Runs `work` as the Emacs task, cancelling the one before.
 116    func runInEmacs(_ work: @escaping @MainActor () async -> Void) {
 117        emacsTask?.cancel()
 118        emacsSerial += 1
 119        let serial = emacsSerial
 120        emacsTask = Task {
 121            await work()
 122            if emacsSerial == serial { emacsTask = nil }
 123        }
 124    }
 125
 126    /// An app command from a menu, run by the main window.
 127    private(set) var runRequest: (id: String, serial: Int)?
 128    private var runSerial = 0
 129
 130    func run(_ id: String) {
 131        runSerial += 1
 132        runRequest = (id, runSerial)
 133    }
 134
 135    /// A capture waiting for the capture window: the template key and the link properties for
 136    /// its escapes (org-protocol), or the agenda day to schedule the entry on.
 137    var captureRequest: (template: String?, properties: [String: String], day: Int?, serial: Int)?
 138    private var captureSerial = 0
 139
 140    /// Capture from an agenda day, as `org-agenda-capture`: that day is the capture's date, and
 141    /// the entry is scheduled on it. The caller opens the capture window.
 142    func capture(on day: Int) {
 143        captureSerial += 1
 144        captureRequest = (nil, [:], day, captureSerial)
 145    }
 146
 147    /// `org-protocol://capture` and `store-link`, and the widgets' `orgstar://` links.
 148    func handle(protocolURL url: String) {
 149        if let link = URL(string: url).flatMap(AppLink.init(url:)) {
 150            switch link {
 151            case .agenda: run("app.agenda")
 152            case .clock: run("app.clock.goto")
 153            case .entry(let path, let offset): jump(path: path, offset: offset)
 154            case .capture(let template):
 155                captureSerial += 1
 156                captureRequest = (template, [:], nil, captureSerial)
 157                run("app.capture")
 158            }
 159            return
 160        }
 161        switch OrgProtocol.parse(url) {
 162        case .capture(let template, let properties):
 163            captureSerial += 1
 164            captureRequest = (template, properties, nil, captureSerial)
 165            run("app.capture")
 166        case .storeLink(let link, let title):
 167            storeLink(StoredLink(link: link, description: title))
 168            NSPasteboard.general.clearContents()
 169            NSPasteboard.general.setString(link, forType: .string)
 170        case nil:
 171            show(String(localized: "orgstar handles org-protocol capture and store-link"))
 172        }
 173    }
 174
 175    func jump(path: String, offset: Int) {
 176        jumpID += 1
 177        jumpRequest = (path, offset, jumpID)
 178    }
 179
 180    func show(_ text: String) {
 181        message = text
 182        messages.append(text)
 183        if messages.count > 100 { messages.removeFirst(messages.count - 100) }
 184        AccessibilityNotification.Announcement(text).post()
 185        // A local monitor sees an event before it is handled, so a message the key or click
 186        // itself shows is set after this clears the last one.
 187        if inputMonitor == nil {
 188            inputMonitor = NSEvent.addLocalMonitorForEvents(matching: [.keyDown, .leftMouseDown, .rightMouseDown]) { [weak self] event in
 189                MainActor.assumeIsolated {
 190                    if self?.message != nil { self?.message = nil }
 191                }
 192                return event
 193            }
 194        }
 195    }
 196}
 197
 198struct PromptRequest: Identifiable {
 199    let id = UUID()
 200    let prompt: Prompt
 201    let reply: (String?) -> Void
 202}
 203
 204@MainActor
 205final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDelegate {
 206    var session: DocumentSession?
 207    var commands: AppCommands?
 208    #if APPSTORE
 209    var workspace: WorkspaceModel?
 210    #else
 211    let updates = Updates()
 212    #endif
 213
 214    func applicationDidFinishLaunching(_ notification: Notification) {
 215        DockIcon.start()
 216        if SystemReminderCenter.isAvailable { UNUserNotificationCenter.current().delegate = self }
 217        #if !APPSTORE
 218        updates.start()
 219        #endif
 220    }
 221
 222    #if APPSTORE
 223    /// A subscription may have lapsed or renewed while the app was in the background.
 224    func applicationDidBecomeActive(_ notification: Notification) {
 225        Task { await ProStore.shared.refresh() }
 226    }
 227    #endif
 228
 229    /// `:session` interpreters end with the app.
 230    func applicationWillTerminate(_ notification: Notification) {
 231        #if !APPSTORE
 232        BabelSessions.shared.stopAll()
 233        #endif
 234    }
 235
 236    /// Reminders show while Orgstar is in front too.
 237    nonisolated func userNotificationCenter(
 238        _ center: UNUserNotificationCenter, willPresent notification: UNNotification
 239    ) async -> UNNotificationPresentationOptions {
 240        [.banner, .sound, .list]
 241    }
 242
 243    /// Clicking a reminder shows its entry.
 244    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
 245        let info = response.notification.request.content.userInfo
 246        guard let path = info["path"] as? String, let offset = info["offset"] as? Int else { return }
 247        await MainActor.run {
 248            NSApp.activate()
 249            commands?.jump(path: path, offset: offset)
 250        }
 251    }
 252
 253    /// Files opened from Finder, `open`, or a drop on the Dock icon: each opens as a buffer.
 254    /// Ones that arrive before the window is ready wait for it (`pendingOpens`).
 255    static var pendingOpens: [String] = []
 256
 257    func application(_ application: NSApplication, open urls: [URL]) {
 258        let paths = urls.filter(\.isFileURL).map(\.path)
 259        let links = urls.filter { $0.scheme == "org-protocol" || $0.scheme == AppLink.scheme }.map(\.absoluteString)
 260        guard let commands, let session else {
 261            Self.pendingOpens += paths
 262            Self.pendingLinks += links
 263            return
 264        }
 265        NSApp.activate()
 266        for path in paths { session.open(path) }
 267        for link in links { commands.handle(protocolURL: link) }
 268    }
 269
 270    /// org-protocol and orgstar:// links that arrive before the window is ready.
 271    static var pendingLinks: [String] = []
 272
 273    func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true }
 274
 275    func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
 276        guard let session else { return .terminateNow }
 277        #if APPSTORE
 278        BufferRestore.save(session, workspace: workspace)
 279        #else
 280        BufferRestore.save(session)
 281        #endif
 282        guard UnsavedChanges.resolve(session, paths: session.openPaths) else { return .terminateCancel }
 283        #if !APPSTORE
 284        // Files saved since their folder's last automatic commit are committed before quitting.
 285        if GitAutoCommit.shared.hasPending {
 286            Task {
 287                await GitAutoCommit.shared.flush()
 288                sender.reply(toApplicationShouldTerminate: true)
 289            }
 290            return .terminateLater
 291        }
 292        #endif
 293        return .terminateNow
 294    }
 295}
 296
 297/// Unsaved edits when leaving a file or quitting.
 298@MainActor
 299enum UnsavedChanges {
 300    /// Whether the open file can be left: saved in automatic mode, or as the user chooses in
 301    /// explicit mode. A save that fails or conflicts keeps the file open.
 302    static func resolve(_ session: DocumentSession) -> Bool {
 303        guard session.isDirty else { return true }
 304        if session.saveMode == .automatic { return session.save() }
 305        let alert = NSAlert()
 306        alert.messageText = session.path.map { String(localized: "Save changes to \(($0 as NSString).lastPathComponent)?") }
 307            ?? String(localized: "Save changes to this file?")
 308        alert.informativeText = String(localized: "Your changes will be lost if you don't save them.")
 309        alert.addButton(withTitle: String(localized: "Save"))
 310        alert.addButton(withTitle: String(localized: "Don't Save"))
 311        alert.addButton(withTitle: String(localized: "Cancel"))
 312        switch alert.runModal() {
 313        case .alertFirstButtonReturn: return session.save()
 314        case .alertSecondButtonReturn: return true
 315        default: return false
 316        }
 317    }
 318
 319    /// Whether the buffers of `paths` can be closed: saved in automatic mode, or as the user
 320    /// chooses for all of them in explicit mode.
 321    static func resolve(_ session: DocumentSession, paths: [String]) -> Bool {
 322        let dirty = paths.filter(session.dirtyPaths.contains)
 323        guard !dirty.isEmpty else { return true }
 324        if session.saveMode == .automatic { return dirty.map(session.save).allSatisfy { $0 } }
 325        if dirty == [session.path] { return resolve(session) }
 326        let alert = NSAlert()
 327        alert.messageText = String(localized: "Save changes to \(dirty.count) files?")
 328        alert.informativeText = dirty.map { ($0 as NSString).lastPathComponent }.joined(separator: ", ")
 329        alert.addButton(withTitle: String(localized: "Save All"))
 330        alert.addButton(withTitle: String(localized: "Don't Save"))
 331        alert.addButton(withTitle: String(localized: "Cancel"))
 332        switch alert.runModal() {
 333        case .alertFirstButtonReturn: return dirty.map(session.save).allSatisfy { $0 }
 334        case .alertSecondButtonReturn: return true
 335        default: return false
 336        }
 337    }
 338}
 339
 340/// The open buffers, their order and carets, kept for the next launch.
 341@MainActor
 342enum BufferRestore {
 343    private static let key = "openBuffers"
 344
 345    struct State: Codable {
 346        var paths: [String]
 347        var current: String?
 348        var carets: [String: Int]
 349        /// In the Mac App Store build, bookmarks of the files outside every folder, which the
 350        /// sandbox would otherwise keep orgstar out of after relaunch.
 351        var bookmarks: [String: Data]?
 352    }
 353
 354    /// `bookmarking` says which paths get a bookmark. A path still open keeps the bookmark it
 355    /// has when no new one is made.
 356    static func save(_ session: DocumentSession, bookmarking: (String) -> Bool = { _ in false }, defaults: UserDefaults = .standard) {
 357        var carets: [String: Int] = [:]
 358        for path in session.openPaths { carets[path] = session.caret(of: path) }
 359        let previous = defaults.data(forKey: key).flatMap { try? JSONDecoder().decode(State.self, from: $0) }?.bookmarks ?? [:]
 360        var bookmarks: [String: Data] = [:]
 361        for path in session.openPaths {
 362            bookmarks[path] = (bookmarking(path) ? SecurityBookmark.make(URL(fileURLWithPath: path)) : nil) ?? previous[path]
 363        }
 364        let state = State(paths: session.openPaths, current: session.path, carets: carets, bookmarks: bookmarks.isEmpty ? nil : bookmarks)
 365        if let data = try? JSONEncoder().encode(state) { defaults.set(data, forKey: key) }
 366    }
 367
 368    #if APPSTORE
 369    /// Saves with bookmarks for the files outside `workspace`'s folders and grants.
 370    static func save(_ session: DocumentSession, workspace: WorkspaceModel?) {
 371        save(session, bookmarking: { workspace?.contains(URL(fileURLWithPath: $0)) != true })
 372    }
 373    #endif
 374
 375    /// Opens the buffers that were open, in order, and returns the carets to show them at.
 376    static func restore(_ session: DocumentSession, defaults: UserDefaults = .standard) -> [String: Int] {
 377        guard let data = defaults.data(forKey: key), var state = try? JSONDecoder().decode(State.self, from: data) else { return [:] }
 378        // A bookmarked file comes back with access, at the path it has now.
 379        for (path, bookmark) in state.bookmarks ?? [:] {
 380            guard let moved = SecurityBookmark.resolve(bookmark)?.url.path, moved != path else { continue }
 381            state.paths = state.paths.map { $0 == path ? moved : $0 }
 382            if state.current == path { state.current = moved }
 383            state.carets[moved] = state.carets.removeValue(forKey: path)
 384        }
 385        let existing = state.paths.filter { FileManager.default.fileExists(atPath: $0) }
 386        for path in existing { session.open(path) }
 387        if let current = state.current, existing.contains(current) { session.open(current) }
 388        return state.carets
 389    }
 390}
 391
 392@main
 393struct OrgstarApp: App {
 394    @NSApplicationDelegateAdaptor private var delegate: AppDelegate
 395    @State private var workspace = Result {
 396        try WorkspaceModel(directory: WorkspaceModel.defaultDirectory, settings: .with(todoKeywords: Preferences.orgSettings))
 397    }
 398    @State private var commands = AppCommands()
 399    @State private var clock = ClockModel()
 400    @State private var scheduler = SystemReminderCenter.isAvailable ? ReminderScheduler(center: SystemReminderCenter()) : nil
 401    @State private var session: DocumentSession = {
 402        let session = DocumentSession()
 403        session.defaults = Preferences.orgSettings
 404        return session
 405    }()
 406
 407    init() {
 408        PDFExport.mathJaxURL = OrgMathJax.script
 409        DiagramBlocks.vizURL = OrgMathJax.viz
 410        DiagramBlocks.mermaidURL = OrgMathJax.mermaid
 411        #if APPSTORE
 412        AgendaSnapshot.useGroupContainer = true
 413        EmacsFallback.offered = false
 414        _ = FolderGrants.shared
 415        ProStore.shared.start()
 416        #else
 417        DocumentSession.programs = Programs()
 418        MacPro.resolve()
 419        MacPro.renewInBackground()
 420        #endif
 421        // `org-sbe` in table formulas runs blocks, so it needs Babel as source blocks do.
 422        TableBlocks.allowed = { ProAccess.isUnlockedNow }
 423        // Debug builds, and runs with ORGSTAR_PERF set: main-thread stalls in the console.
 424        #if DEBUG
 425        Perf.watchMainThread()
 426        #else
 427        if ProcessInfo.processInfo.environment["ORGSTAR_PERF"] != nil { Perf.watchMainThread() }
 428        #endif
 429    }
 430
 431    var body: some Scene {
 432        Window("orgstar", id: "main") {
 433            switch workspace {
 434            case .success(let model):
 435                ContentView(workspace: model, session: session, commands: commands, scheduler: scheduler, clock: clock)
 436                    .environment(\.orgTheme, ConfigSync.shared.theme)
 437                    .tint(ConfigSync.shared.theme.color("accent"))
 438                    .onAppear {
 439                        delegate.session = session
 440                        delegate.commands = commands
 441                        #if APPSTORE
 442                        delegate.workspace = model
 443                        #else
 444                        GitAutoCommit.shared.roots = { model.rootPaths }
 445                        GitAutoCommit.shared.report = { commands.show($0) }
 446                        session.fileWritten = { GitAutoCommit.shared.fileWritten($0) }
 447                        #endif
 448                        CaptureIntent.environment = (model, session, clock, commands)
 449                    }
 450            case .failure(let error):
 451                ContentUnavailableView("Can't Open the Index", systemImage: "exclamationmark.triangle", description: Text(error.localizedDescription))
 452            }
 453        }
 454        .defaultSize(width: 1280, height: 860)
 455        WindowGroup("Editor", id: "editor") {
 456            if case .success = workspace {
 457                EditorWindowView(session: session, commands: commands)
 458                    .environment(\.orgTheme, ConfigSync.shared.theme)
 459                    .tint(ConfigSync.shared.theme.color("accent"))
 460            }
 461        }
 462        .defaultSize(width: 900, height: 700)
 463        .commandsRemoved()
 464        Window("Agenda", id: "agenda") {
 465            if case .success(let model) = workspace {
 466                AgendaView(workspace: model, session: session, commands: commands, scheduler: scheduler, clock: clock)
 467                    .environment(\.orgTheme, ConfigSync.shared.theme)
 468                    .tint(ConfigSync.shared.theme.color("accent"))
 469            }
 470        }
 471        .defaultSize(width: 760, height: 720)
 472        Window("Board", id: "board") {
 473            if case .success(let model) = workspace {
 474                BoardView(workspace: model, session: session, commands: commands)
 475                    .environment(\.orgTheme, ConfigSync.shared.theme)
 476                    .tint(ConfigSync.shared.theme.color("accent"))
 477            }
 478        }
 479        .defaultSize(width: 1100, height: 700)
 480        Window("Node Graph", id: "graph") {
 481            if case .success(let model) = workspace {
 482                RoamGraphWindow(workspace: model, session: session, commands: commands)
 483                    .tint(ConfigSync.shared.theme.color("accent"))
 484            }
 485        }
 486        .defaultSize(width: 900, height: 700)
 487        Window("Clock Report", id: "clock-report") {
 488            if case .success(let model) = workspace {
 489                ClockReportView(workspace: model, session: session)
 490                    .environment(\.orgTheme, ConfigSync.shared.theme)
 491                    .tint(ConfigSync.shared.theme.color("accent"))
 492            }
 493        }
 494        .defaultSize(width: 860, height: 560)
 495        Window("Capture", id: "capture") {
 496            if case .success(let model) = workspace {
 497                CaptureView(workspace: model, session: session, commands: commands, clock: clock)
 498                    .environment(\.orgTheme, ConfigSync.shared.theme)
 499                    .tint(ConfigSync.shared.theme.color("accent"))
 500            }
 501        }
 502        .windowResizability(.contentSize)
 503        .windowLevel(.floating)
 504        .commands {
 505            CommandGroup(after: .newItem) {
 506                Button("Add Folder…") { commands.showingFolderPicker = true }
 507                    .keyboardShortcut("o", modifiers: [.command, .shift])
 508                Button("Quick Open…") { commands.showingQuickOpen = true }
 509                    .keyboardShortcut("p")
 510                Button("Command Palette…") { commands.showingPalette = true }
 511                    .keyboardShortcut("p", modifiers: [.command, .shift])
 512            }
 513            CommandGroup(after: .saveItem) {
 514                Menu("Export") {
 515                    ForEach(EditorCommands.all.filter { $0.id.hasPrefix("app.export.") && !hiddenCommandIDs.contains($0.id) }, id: \.id) { command in
 516                        Button(command.localizedTitle) { commands.run(command.id) }
 517                    }
 518                }
 519                .disabled(session.path == nil)
 520                Menu("Publish") {
 521                    ForEach(EditorCommands.all.filter { $0.id.hasPrefix("app.publish") }, id: \.id) { command in
 522                        Button(command.localizedTitle) { commands.run(command.id) }
 523                    }
 524                }
 525                Divider()
 526                Button("Revert to File on Disk") { commands.run("app.revert") }
 527                    .disabled(session.path == nil)
 528                Button("Resolve Sync Conflicts…") { commands.run("app.sync-conflicts") }
 529                    .disabled(session.path == nil)
 530                Button("History…") { commands.run("app.recovery") }
 531                    .disabled(session.path == nil)
 532            }
 533            CommandGroup(replacing: .saveItem) {
 534                Button("Close Buffer") {
 535                    // ⌘W closes the buffer in the main window, and other windows themselves.
 536                    if let key = NSApp.keyWindow, key.identifier?.rawValue.contains("main") != true {
 537                        key.performClose(nil)
 538                    } else {
 539                        commands.run("app.buffer.kill")
 540                    }
 541                }
 542                .keyboardShortcut("w")
 543                Button("Close Window") { NSApp.keyWindow?.performClose(nil) }
 544                    .keyboardShortcut("w", modifiers: [.command, .shift])
 545                Divider()
 546                Button("Save") {
 547                    if !session.save(), session.conflict != nil { commands.showingConflict = true }
 548                }
 549                .keyboardShortcut("s")
 550                .disabled(session.path == nil || session.isReadOnly)
 551                Button("Save All") { commands.run("app.save-all") }
 552                    .keyboardShortcut("s", modifiers: [.command, .option])
 553                    .disabled(session.dirtyPaths.isEmpty)
 554            }
 555            CommandGroup(after: .sidebar) {
 556                Button("Split Pane Below") { commands.run("app.split-below") }
 557                    .keyboardShortcut("2", modifiers: [.command, .control])
 558                Button("Split Pane Right") { commands.run("app.split-right") }
 559                    .keyboardShortcut("3", modifiers: [.command, .control])
 560                Button("Close Pane") { commands.run("app.pane-close") }
 561                    .keyboardShortcut("0", modifiers: [.command, .control])
 562                Button("Close Other Panes") { commands.run("app.pane-only") }
 563                    .keyboardShortcut("1", modifiers: [.command, .control])
 564                Button("Next Pane") { commands.run("app.pane-next") }
 565                    .keyboardShortcut("`", modifiers: [.command, .option])
 566                Divider()
 567                ViewMenuToggles(commands: commands)
 568                Divider()
 569                Button("Messages") { commands.run("app.messages") }
 570            }
 571            CommandGroup(after: .pasteboard) {
 572                Divider()
 573                FindMenu(commands: commands)
 574                MacroMenu(commands: commands)
 575            }
 576            CommandGroup(after: .textEditing) {
 577                Button("Cancel Running Task") { commands.run("app.babel.cancel") }
 578                    .keyboardShortcut(".")
 579                    .disabled(!session.isRunningBabel && commands.emacsTask == nil)
 580                Button("Search Notes") { commands.focusSearch = true }
 581                    .keyboardShortcut("f", modifiers: [.command, .shift])
 582            }
 583            CommandGroup(before: .windowList) {
 584                AgendaMenuItem()
 585                Divider()
 586                Button("Switch to Buffer…") { commands.run("app.buffer.switch") }
 587                Button("Next Buffer") { commands.run("app.buffer.next") }
 588                    .keyboardShortcut("]", modifiers: [.command, .shift])
 589                Button("Previous Buffer") { commands.run("app.buffer.previous") }
 590                    .keyboardShortcut("[", modifiers: [.command, .shift])
 591                Divider()
 592            }
 593            CommandGroup(after: .newItem) {
 594                Button("Capture…") { commands.run("app.capture") }
 595                    .keyboardShortcut("n", modifiers: [.command, .shift])
 596                Button("New File from Template…") { commands.run("app.new-file-from-template") }
 597                Button("New Window") { commands.run("app.window-new") }
 598                    .keyboardShortcut("n", modifiers: [.command, .option])
 599            }
 600        }
 601        .commands {
 602            CommandMenu("Org") {
 603                ClockMenu(commands: commands, clock: clock)
 604                Divider()
 605                OrgMenuItems(commands: commands)
 606            }
 607        }
 608        .commands {
 609            CommandGroup(after: .appSettings) {
 610                Button("Edit Config File") { commands.jump(path: UserConfig.configFile.path, offset: 0) }
 611                    .keyboardShortcut(",", modifiers: [.command, .option])
 612            }
 613            #if !APPSTORE
 614            CommandGroup(after: .appInfo) {
 615                CheckForUpdatesItem(updates: delegate.updates)
 616            }
 617            #endif
 618            CommandGroup(replacing: .help) {
 619                Button("orgstar Manual") { NSWorkspace.shared.open(Manual.home) }
 620                Button("Keys") { NSWorkspace.shared.open(Manual.keys) }
 621                Divider()
 622                Button("What's New in orgstar") { commands.whatsNew = WhatsNew.releases.first }
 623                    .disabled(!commands.mainWindowOpen)
 624            }
 625        }
 626        Settings {
 627            #if APPSTORE
 628            SettingsView(commands: commands, workspace: try? workspace.get())
 629            #else
 630            SettingsView(commands: commands, workspace: try? workspace.get(), updates: delegate.updates)
 631            #endif
 632        }
 633    }
 634}
 635
 636/// The Org menu: every org command and the app's commands for entries and notes, in submenus by
 637/// subject, with the keys that run them in the current keymap.
 638struct OrgMenuItems: View {
 639    let commands: AppCommands
 640
 641    /// Submenus and the command id prefixes they hold, in menu order. A command goes in the
 642    /// first submenu with a prefix it starts with.
 643    static let groups: [(title: LocalizedStringKey, prefixes: [String])] = [
 644        ("Visibility", ["org.cycle", "org.fold.", "org.narrow.", "org.widen", "org.sparse-tree", "org.toggle-inline-images", "org.latex-preview"]),
 645        ("Headings", ["org.heading.", "org.subtree.", "org.element.", "org.goto", "org.sort", "org.archive.", "app.refile", "app.archive"]),
 646        ("TODO and Tags", ["org.todo.", "org.priority.", "org.tags.", "org.effort.", "app.rename-"]),
 647        ("Properties and Columns", ["org.property.", "org.columns", "org.drawer."]),
 648        ("Dates and Timers", ["org.schedule", "org.deadline", "org.timestamp.", "org.timer."]),
 649        ("Lists", ["org.item.", "org.checkbox."]),
 650        ("Tables", ["org.table", "app.table-", "app.plot"]),
 651        ("Links and Footnotes", ["org.link.", "org.id.", "org.footnote."]),
 652        ("Blocks", ["org.babel.", "org.structure-template", "org.edit-special", "org.dblock.", "org.clock.report", "org.denote."]),
 653        ("Text", ["org.emphasize", "org.fill-"]),
 654        ("Attachments", ["app.attach."]),
 655        ("Notes", ["app.dailies.", "app.node."]),
 656        ("Encryption", ["app.crypt."]),
 657    ]
 658
 659    private static func group(of id: String) -> Int? {
 660        groups.firstIndex { $0.prefixes.contains { id.hasPrefix($0) } }
 661    }
 662
 663    private static let shown = EditorCommands.all.filter { ($0.id.hasPrefix("org.") || group(of: $0.id) != nil) && !hiddenCommandIDs.contains($0.id) }
 664
 665    var body: some View {
 666        // Commands that fit no subject, such as Act at Point, come first.
 667        ForEach(Self.shown.filter { Self.group(of: $0.id) == nil }, id: \.id) { item($0) }
 668        Divider()
 669        ForEach(Self.groups.indices, id: \.self) { index in
 670            Menu(Self.groups[index].title) {
 671                ForEach(Self.shown.filter { Self.group(of: $0.id) == index }, id: \.id) { item($0) }
 672            }
 673        }
 674    }
 675
 676    private func item(_ command: EditorCommand) -> some View {
 677        Button {
 678            if command.id.hasPrefix("org.") { commands.editor?.run(command.id) } else { commands.run(command.id) }
 679        } label: {
 680            Text(command.localizedTitle)
 681            if let keys = commands.keyLabel(for: command.id) { Text(keys) }
 682        }
 683        .disabled(command.id.hasPrefix("org.") && commands.editor == nil)
 684    }
 685}
 686
 687/// The user manual, as `scripts/publish-docs.sh` publishes it.
 688enum Manual {
 689    static let home = URL(string: "https://files.krz.sh/orgstar/")!
 690    /// The key reference, with every preset's keys.
 691    static let keys = URL(string: "https://files.krz.sh/orgstar/guide/03-keys.html#key-reference")!
 692}
 693
 694/// View ▸ the panes and the focused editor's modes, checked while on.
 695struct ViewMenuToggles: View {
 696    let commands: AppCommands
 697    @AppStorage("backlinksShown") private var backlinksShown = true
 698    @AppStorage("inspectorShown") private var inspectorShown = false
 699
 700    var body: some View {
 701        let outline = commands.outlineShown
 702        let editor = commands.editor
 703        // A key that switches an editor mode shows a message, so the checks follow it.
 704        let _ = commands.message
 705        Toggle("Show Outline", isOn: Binding(get: { outline }, set: { _ in commands.run("app.toggle-outline") }))
 706            .keyboardShortcut("o", modifiers: [.command, .option])
 707        Toggle("Show Backlinks", isOn: $backlinksShown)
 708        Toggle("Show Inspector", isOn: $inspectorShown)
 709            .keyboardShortcut("i", modifiers: [.command, .option])
 710        MarkupToggle()
 711        editorToggle("Truncate Long Lines", "editor.toggle-truncate-lines", editor?.truncatesLines)
 712        editorToggle("Auto Fill", "editor.toggle-auto-fill", editor?.autoFills)
 713        editorToggle("Check Spelling While Typing", "editor.toggle-spell-check", editor?.spellChecking)
 714    }
 715
 716    private func editorToggle(_ title: LocalizedStringKey, _ id: String, _ on: Bool?) -> some View {
 717        Toggle(title, isOn: Binding(get: { on ?? false }, set: { _ in commands.editor?.run(id) }))
 718            .disabled(on == nil)
 719    }
 720}
 721
 722/// View ▸ Show Markup (link brackets and targets, emphasis markers) and Show Line Numbers.
 723struct MarkupToggle: View {
 724    @AppStorage("showTabBar") private var showTabBar = false
 725    @AppStorage("showMarkup") private var showMarkup = false
 726    @AppStorage("showLineNumbers") private var showLineNumbers = false
 727    @AppStorage("lineNumbersType") private var lineNumbersType = "t"
 728
 729    var body: some View {
 730        Toggle("Show Markup", isOn: $showMarkup)
 731            .keyboardShortcut("m", modifiers: [.command, .shift])
 732        Toggle("Show Line Numbers", isOn: $showLineNumbers)
 733            .keyboardShortcut("l", modifiers: [.command, .shift])
 734        Picker("Line Numbers", selection: $lineNumbersType) {
 735            Text("Absolute").tag("t")
 736            Text("Relative").tag("relative")
 737            Text("Visual").tag("visual")
 738        }
 739        Toggle("Show Tab Bar", isOn: $showTabBar)
 740    }
 741}
 742
 743/// Edit ▸ Find: the editor's find bar.
 744struct FindMenu: View {
 745    let commands: AppCommands
 746
 747    var body: some View {
 748        Menu("Find") {
 749            item("Find…", "edit.find", "f")
 750            item("Find and Replace…", "edit.replace", "f", [.command, .option])
 751            item("Find Next", "edit.find-next", "g")
 752            item("Find Previous", "edit.find-previous", "g", [.command, .shift])
 753            item("Use Selection for Find", "edit.use-selection-for-find", "e")
 754            Divider()
 755            Button("Replace in Files…") { commands.run("app.replace-in-files") }
 756                .keyboardShortcut("f", modifiers: [.command, .option, .shift])
 757        }
 758    }
 759
 760    private func item(_ title: String, _ id: String, _ key: KeyEquivalent, _ modifiers: EventModifiers = .command) -> some View {
 761        Button(title) { commands.editor?.run(id) }
 762            .keyboardShortcut(key, modifiers: modifiers)
 763            .disabled(commands.editor == nil)
 764    }
 765}
 766
 767/// Edit ▸ Macros: keyboard macros, with the keys that run them in the current keymap.
 768struct MacroMenu: View {
 769    let commands: AppCommands
 770
 771    var body: some View {
 772        Menu("Macros") {
 773            item("Start Recording", "macro.start")
 774            item("Stop Recording", "macro.end")
 775            item("Run Last Macro", "macro.call")
 776            Divider()
 777            item("Name Last Macro…", "macro.name")
 778            item("Run Macro…", "macro.run")
 779        }
 780    }
 781
 782    private func item(_ title: LocalizedStringKey, _ id: String) -> some View {
 783        Button {
 784            commands.editor?.run(id)
 785        } label: {
 786            Text(title)
 787            if let keys = commands.keyLabel(for: id) { Text(keys) }
 788        }
 789        .disabled(commands.editor == nil)
 790    }
 791}
 792
 793/// Window ▸ Agenda.
 794struct AgendaMenuItem: View {
 795    @Environment(\.openWindow) private var openWindow
 796
 797    var body: some View {
 798        Button("Agenda") { openWindow(id: "agenda") }
 799            .keyboardShortcut("a", modifiers: [.command, .shift])
 800        Button("Board") { openWindow(id: "board") }
 801            .keyboardShortcut("b", modifiers: [.command, .shift])
 802        Button("Graph") { if ProAccess.shared.allows(.roam) { openWindow(id: "graph") } }
 803    }
 804}
 805
 806struct SettingsView: View {
 807    let commands: AppCommands
 808    let workspace: WorkspaceModel?
 809    #if !APPSTORE
 810    let updates: Updates
 811    #endif
 812    @State private var importing = false
 813    #if APPSTORE
 814    @State private var configFolder = UserConfig.directoryOverride
 815    #endif
 816    @Environment(\.openWindow) private var openWindow
 817    @AppStorage("saveMode") private var saveMode = SaveMode.automatic
 818    @AppStorage("keymap") private var preset = KeymapPreset.emacs
 819    @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
 820    @AppStorage("tagsColumn") private var tagsColumn = -77
 821    @AppStorage("headingAfterSubtree") private var headingAfterSubtree = false
 822    @AppStorage("splitLine") private var splitLine = false
 823    @AppStorage("alphabeticalLists") private var alphabeticalLists = true
 824    @AppStorage("fillColumn") private var fillColumn = 80
 825    @AppStorage("hiddenMarkers") private var hiddenMarkers = true
 826    @AppStorage("prettyEntities") private var prettyEntities = true
 827    @AppStorage("startupTruncated") private var startupTruncated = false
 828    @AppStorage("todoKeywords") private var todoKeywords = Preferences.defaultTodoKeywords
 829    @AppStorage("logDone") private var logDone = "nil"
 830    @AppStorage("logIntoDrawer") private var logIntoDrawer = ""
 831    @AppStorage("useSpeedCommands") private var useSpeedCommands = false
 832    @AppStorage("spellCheck") private var spellCheck = false
 833    @AppStorage("completionAuto") private var completionAuto = "preset"
 834    @AppStorage("completionAutoDelay") private var completionAutoDelay = 400
 835    @AppStorage("completionAutoPrefix") private var completionAutoPrefix = 2
 836    @AppStorage("completionStyle") private var completionStyle = "preset"
 837    @AppStorage("completionWords") private var completionWords = false
 838    @AppStorage("enforceTodoDependencies") private var enforceTodoDependencies = false
 839    @AppStorage("enforceTodoCheckboxDependencies") private var enforceTodoCheckboxDependencies = false
 840    @AppStorage("agendaSpan") private var agendaSpan = 10
 841    @AppStorage("agendaStartOffset") private var agendaStartOffset = 0
 842    @AppStorage("agendaSubfolders") private var agendaSubfolders = false
 843    @AppStorage("agendaShowAllDates") private var agendaShowAllDates = false
 844    @AppStorage("habitsOnlyForToday") private var habitsOnlyForToday = true
 845    @AppStorage("agendaDimBlockedTasks") private var agendaDimBlockedTasks = "t"
 846    @AppStorage("calendarEvents") private var calendarEvents = false
 847    @AppStorage("calendarEventCalendars") private var calendarEventCalendars = ""
 848    @State private var calendars: [(id: String, title: String, color: RGBA?)] = []
 849    @AppStorage("agendaReminders") private var agendaReminders = false
 850    @AppStorage("agendaReminderLists") private var agendaReminderLists = ""
 851    @State private var reminderLists: [(id: String, title: String, color: RGBA?)] = []
 852    @AppStorage("reminders") private var reminders = true
 853    @AppStorage("reminderLead") private var reminderLead = 12
 854    @AppStorage("clockIdleTime") private var clockIdleTime = 0
 855    @AppStorage("clockHistoryLength") private var clockHistoryLength = 5
 856    @AppStorage("globalCapture") private var globalCapture = true
 857    @AppStorage("menuBarItem") private var menuBarItem = false
 858    @AppStorage("settingsTab") private var tab = "general"
 859    @AppStorage("showHiddenFiles") private var showHiddenFiles = true
 860    @AppStorage("themeFont") private var themeFont = ""
 861    @AppStorage("themeBodyFont") private var themeBodyFont = ""
 862    @AppStorage("themeFontSize") private var themeFontSize = 13
 863    @AppStorage("themeLineSpacing") private var themeLineSpacing = 2
 864    @AppStorage("themeTextWidth") private var themeTextWidth = 0
 865    @AppStorage("themeHeadingStep") private var themeHeadingStep = 1
 866
 867    /// Installed font families that aren't monospaced, for body text.
 868    private static let proportionalFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in
 869        NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == false
 870    }
 871
 872    /// Installed monospaced font families.
 873    private static let monospacedFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in
 874        NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == true
 875    }
 876
 877    var body: some View {
 878        TabView(selection: $tab) {
 879            Tab("General", systemImage: "gearshape", value: "general") { general }
 880            Tab("Editing", systemImage: "text.alignleft", value: "editing") { editing }
 881            Tab("Appearance", systemImage: "paintpalette", value: "appearance") { appearance }
 882            Tab("Agenda", systemImage: "calendar", value: "agenda") { agenda }
 883            Tab("Capture", systemImage: "tray.and.arrow.down", value: "capture") { capture }
 884            #if !APPSTORE
 885            Tab(value: "git") { GitSettingsForm(workspace: workspace) } label: {
 886                Label { Text("Git", tableName: "DeveloperID") } icon: { Image(systemName: "arrow.triangle.branch") }
 887            }
 888            #endif
 889            #if APPSTORE
 890            Tab("orgstar+", systemImage: "star", value: "pro") { StoreForm() }
 891            #else
 892            Tab("orgstar+", systemImage: "star", value: "pro") { LicenseForm() }
 893            #endif
 894        }
 895        .frame(width: 600)
 896    }
 897
 898    private func editConfig() {
 899        ConfigSync.shared.start()
 900        openWindow(id: "main")
 901        commands.jump(path: UserConfig.configFile.path, offset: 0)
 902    }
 903
 904    #if APPSTORE
 905    /// A folder outside the app's container, such as `~/.config/orgstar` kept with dotfiles.
 906    private func chooseConfigFolder() {
 907        let panel = NSOpenPanel()
 908        panel.canChooseFiles = false
 909        panel.canChooseDirectories = true
 910        panel.canCreateDirectories = true
 911        panel.directoryURL = configFolder ?? ConfigFolder.suggested
 912        panel.message = String(localized: "Choose the folder for config.toml and orgstar's other configuration files.", comment: "Choose Configuration Folder panel")
 913        guard panel.runModal() == .OK, let url = panel.url else { return }
 914        if !ConfigFolder.set(url) {
 915            GrantAccess.tell(String(localized: "orgstar can't keep \(OrgPaths.abbreviatingWithTilde(url.path)) as the configuration folder.", comment: "Alert when the chosen configuration folder can't be saved"),
 916                             String(localized: "Access lasts until orgstar quits.", comment: "Alert when a folder grant or the configuration folder can't be saved"))
 917        }
 918        useConfigFolder(url)
 919    }
 920
 921    /// Reads and writes the configuration in `url`, or with nil in the default folder.
 922    private func useConfigFolder(_ url: URL?) {
 923        if url == nil { ConfigFolder.clear() }
 924        UserConfig.directoryOverride = url
 925        configFolder = url
 926        ConfigSync.shared.move(to: UserConfig.configFile)
 927    }
 928    #endif
 929
 930    private var general: some View {
 931        Form {
 932            Section {
 933                LabeledContent("config.toml") {
 934                    HStack {
 935                        Button("Edit in orgstar") { editConfig() }
 936                        Button("Open with Default App") { NSWorkspace.shared.open(UserConfig.configFile) }
 937                        Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([UserConfig.configFile]) }
 938                    }
 939                }
 940                #if APPSTORE
 941                LabeledContent("Folder") {
 942                    HStack {
 943                        Button("Choose Configuration Folder…") { chooseConfigFolder() }
 944                        if configFolder != nil { Button("Use Default Folder") { useConfigFolder(nil) } }
 945                    }
 946                }
 947                #endif
 948                LabeledContent("Emacs") {
 949                    Button("Import from Emacs…") { importing = true }
 950                }
 951            } footer: {
 952                Text("Every setting here is also in \(UserConfig.configFile.path), which you can edit, share or keep with your dotfiles. Changes in either place show up in the other.")
 953                    .settingsFooter()
 954            }
 955            #if !APPSTORE
 956            if updates.canCheck {
 957                Section {
 958                    Toggle(isOn: Binding(get: { updates.automatically }, set: { updates.automatically = $0 })) { Text("Check for updates automatically", tableName: "DeveloperID") }
 959                } footer: {
 960                    Text("Once a day, from the app's own feed. orgstar ▸ Check for Updates… checks now.", tableName: "DeveloperID")
 961                        .settingsFooter()
 962                }
 963            }
 964            #endif
 965            Section {
 966                Picker("Save files", selection: $saveMode) {
 967                    Text("Automatically, when typing stops").tag(SaveMode.automatic)
 968                    Text("Only with File ▸ Save (⌘S)").tag(SaveMode.explicit)
 969                }
 970                .pickerStyle(.radioGroup)
 971            }
 972            Section {
 973                Picker("Keys", selection: $preset) {
 974                    ForEach(KeymapPreset.allCases, id: \.self) { Text($0.title).tag($0) }
 975                }
 976                Toggle("Show hidden files and folders", isOn: $showHiddenFiles)
 977                Toggle("Keep orgstar in the menu bar", isOn: $menuBarItem)
 978                    .help("Capture, the agenda, today's entries and the clock, from any app. When off, the menu bar shows orgstar only while a clock runs.")
 979                Picker("Option as Meta", selection: $optionAsMeta) {
 980                    Text("Left Option").tag(OptionAsMeta.left.rawValue)
 981                    Text("Right Option").tag(OptionAsMeta.right.rawValue)
 982                    Text("Both").tag(OptionAsMeta([.left, .right]).rawValue)
 983                    Text("Neither").tag(0)
 984                }
 985            } footer: {
 986                Text("Your own bindings go in \(KeymapLoader.userFile.path), on top of the preset.")
 987                    .settingsFooter()
 988            }
 989        }
 990        .formStyle(.grouped)
 991        .frame(height: 330)
 992        .sheet(isPresented: $importing) { EmacsImportView(workspace: workspace) }
 993    }
 994
 995    private var editing: some View {
 996        Form {
 997            Section {
 998                Picker("Tags", selection: $tagsColumn) {
 999                    Text("Aligned to end at column 77").tag(-77)
1000                    Text("One space after the title").tag(0)
1001                }
1002                .help(Text(verbatim: "org-tags-column"))
1003                Toggle(isOn: $headingAfterSubtree) { keyed("New headings go after the subtree", "org.heading.insert") }
1004                    .help(Text(verbatim: "org-insert-heading-respect-content"))
1005                Toggle(isOn: $splitLine) { keyed("New headings and items split the line at the caret", "org.heading.insert") }
1006                    .help(Text(verbatim: "org-M-RET-may-split-line"))
1007                Toggle("Lists can use letters (a. b. c.)", isOn: $alphabeticalLists)
1008                    .help(Text(verbatim: "org-list-allow-alphabetical"))
1009                Stepper(value: $fillColumn, in: 40...200) { keyed("Fill Paragraph wraps lines at column \(fillColumn)", "org.fill-paragraph") }
1010                    .help(Text(verbatim: "fill-column"))
1011            }
1012            Section {
1013                Toggle("Long lines run off the edge instead of wrapping", isOn: $startupTruncated)
1014                    .help(Text(verbatim: "org-startup-truncated"))
1015            } footer: {
1016                Text("Applies to files as they open. View ▸ Truncate Long Lines switches the current file.")
1017                    .settingsFooter()
1018            }
1019            Section {
1020                Toggle("Emacs hides emphasis markers", isOn: $hiddenMarkers)
1021                    .help(Text(verbatim: "org-hide-emphasis-markers"))
1022                Toggle("Emacs shows entities as characters", isOn: $prettyEntities)
1023                    .help(Text(verbatim: "org-pretty-entities"))
1024            } footer: {
1025                Text("Tags, tables and Fill Paragraph measure text as your Emacs displays it, so both write the same file.")
1026                    .settingsFooter()
1027            }
1028            Section {
1029                TextField("Default TODO keywords", text: $todoKeywords, axis: .vertical)
1030            } footer: {
1031                Text("For files without #+TODO, in #+TODO syntax, one sequence per line. Takes effect when orgstar restarts.")
1032                    .settingsFooter()
1033            }
1034            Section {
1035                Toggle("Entries can't be done before their TODO children", isOn: $enforceTodoDependencies)
1036                    .help(Text(verbatim: "org-enforce-todo-dependencies"))
1037                Toggle("Entries can't be done with unchecked boxes", isOn: $enforceTodoCheckboxDependencies)
1038                    .help(Text(verbatim: "org-enforce-todo-checkbox-dependencies"))
1039            } footer: {
1040                Text("Under a parent with the ORDERED property (Org ▸ Properties and Columns ▸ Toggle ORDERED Property), TODO children are also done in order.")
1041                    .settingsFooter()
1042            }
1043            Section {
1044                Picker("When an entry is done", selection: $logDone) {
1045                    Text("Record nothing").tag("nil")
1046                    Text("Record the time, as CLOSED").tag("time")
1047                    Text("Record the time and ask for a note").tag("note")
1048                }
1049                .help(Text(verbatim: "org-log-done"))
1050                Toggle("State notes go in a LOGBOOK drawer", isOn: logIntoDrawerOn)
1051                    .help(Text(verbatim: "org-log-into-drawer"))
1052            } footer: {
1053                Text("Keyword flags such as DONE(d!) and #+STARTUP words in a file override these. org-log-reschedule and org-log-redeadline are in config.toml.")
1054                    .settingsFooter()
1055            }
1056            Section {
1057                Toggle("Speed keys: single letters at the start of a heading line run commands", isOn: $useSpeedCommands)
1058                    .help(Text(verbatim: "org-use-speed-commands"))
1059                Toggle("Check spelling while typing", isOn: $spellCheck)
1060                    .help(Text(verbatim: "spell-check"))
1061            } footer: {
1062                Text("Spell checking applies to files as they open; Check Spelling While Typing switches the current file. Code, links, dates, tags and keywords aren't checked.")
1063                    .settingsFooter()
1064            }
1065            Section {
1066                Picker("Completion list opens", selection: $completionAuto) {
1067                    Text("As the keys do (by itself with Doom)").tag("preset")
1068                    Text("By itself as you type").tag("on")
1069                    Text("Only with a key").tag("off")
1070                }
1071                .help(Text(verbatim: "completion-auto"))
1072                Stepper("After a pause of \(completionAutoDelay) ms", value: $completionAutoDelay, in: 0...2000, step: 50)
1073                    .help(Text(verbatim: "completion-auto-delay"))
1074                Stepper("Once \(completionAutoPrefix) characters are typed", value: $completionAutoPrefix, in: 1...10)
1075                    .help(Text(verbatim: "completion-auto-prefix"))
1076                Picker("Candidates", selection: $completionStyle) {
1077                    Text("As the keys do (letters in order with Doom)").tag("preset")
1078                    Text("Start with what's typed").tag("prefix")
1079                    Text("Have its letters in order, best first").tag("fuzzy")
1080                }
1081                .help(Text(verbatim: "completion-style"))
1082                Toggle("The list offers words from open files and folders", isOn: $completionWords)
1083                    .help(Text(verbatim: "completion-words"))
1084            } header: {
1085                Text("Completion")
1086            } footer: {
1087                Text("Doom's keys open the list by itself and match letters in order, as Doom's corfu does; the Emacs and Mac keys do neither unless set here. Expand Word completes the word before the caret from your files whatever is set.")
1088                    .settingsFooter()
1089            }
1090        }
1091        .formStyle(.grouped)
1092        .frame(height: 860)
1093    }
1094
1095    /// `label`, then the keys that run `command` in the current preset, if any.
1096    private func keyed(_ label: LocalizedStringKey, _ command: String) -> some View {
1097        HStack(spacing: 6) {
1098            Text(label)
1099            if let keys = commands.keyLabel(for: command) {
1100                Text(verbatim: keys).font(.system(.body, design: .monospaced)).foregroundStyle(.secondary)
1101            }
1102        }
1103    }
1104
1105    /// `org-log-into-drawer` as a switch: on is "LOGBOOK" (Emacs's t); a drawer name of its own counts as on.
1106    private var logIntoDrawerOn: Binding<Bool> {
1107        Binding(get: { !logIntoDrawer.isEmpty }, set: { logIntoDrawer = $0 ? "LOGBOOK" : "" })
1108    }
1109
1110    private var appearance: some View {
1111        Form {
1112            ThemePickerSection()
1113            AppIconSection()
1114            Section {
1115                Picker("Font", selection: $themeFont) {
1116                    Text("System monospaced").tag("")
1117                    Divider()
1118                    ForEach(Self.monospacedFamilies, id: \.self) { Text($0).tag($0) }
1119                    if !themeFont.isEmpty, !Self.monospacedFamilies.contains(themeFont) { Text(themeFont).tag(themeFont) }
1120                }
1121                Picker("Body font", selection: $themeBodyFont) {
1122                    Text("Same as Font").tag("")
1123                    Text("System").tag("system")
1124                    Divider()
1125                    ForEach(Self.proportionalFamilies, id: \.self) { Text($0).tag($0) }
1126                    if !["", "system"].contains(themeBodyFont), !Self.proportionalFamilies.contains(themeBodyFont) { Text(themeBodyFont).tag(themeBodyFont) }
1127                }
1128                Stepper("Size: \(themeFontSize) pt", value: $themeFontSize, in: 8...36)
1129                Stepper("Line spacing: \(themeLineSpacing) pt", value: $themeLineSpacing, in: 0...16)
1130                Picker("Text width", selection: $themeTextWidth) {
1131                    Text("Whole editor").tag(0)
1132                    ForEach([60, 70, 80, 90, 100, 120], id: \.self) { Text("\($0) columns").tag($0) }
1133                    if ![0, 60, 70, 80, 90, 100, 120].contains(themeTextWidth) { Text("\(themeTextWidth) columns").tag(themeTextWidth) }
1134                }
1135                Stepper("Headings grow by \(themeHeadingStep) pt a level", value: $themeHeadingStep, in: 0...8)
1136            } footer: {
1137                Text("Tags and tables line up in columns, so Font should be monospaced. With a body font, prose uses it while tables, code, dates, tags and drawers keep Font.")
1138                    .settingsFooter()
1139            }
1140            Section {
1141                LabeledContent("Colors") {
1142                    HStack {
1143                        Button("Edit in config.toml") { editConfig() }
1144                        Button("Show Default Theme") {
1145                            openWindow(id: "main")
1146                            commands.jump(path: UserConfig.directory.appendingPathComponent("default-theme.toml").path, offset: 0)
1147                        }
1148                    }
1149                }
1150            } footer: {
1151                Text("Set colors under [theme] (both appearances), [theme.light] or [theme.dark] in config.toml, and TODO keyword colors under [theme.todo]. default-theme.toml lists every color with the default theme's values.")
1152                    .settingsFooter()
1153            }
1154        }
1155        .formStyle(.grouped)
1156        .frame(height: 620)
1157    }
1158
1159    private var agenda: some View {
1160        Form {
1161            Section {
1162                Stepper("Agenda shows \(agendaSpan) days", value: $agendaSpan, in: 1...366)
1163                Stepper(agendaStartOffset == 0 ? "Agenda starts today" : "Agenda starts \(-agendaStartOffset) days before today", value: $agendaStartOffset, in: -14...0)
1164                Toggle("Include files in subfolders", isOn: $agendaSubfolders)
1165                Toggle("Show days without entries", isOn: $agendaShowAllDates)
1166                Toggle("Habits only today", isOn: $habitsOnlyForToday)
1167                Picker("Blocked entries", selection: $agendaDimBlockedTasks) {
1168                    Text("Dimmed").tag("t")
1169                    Text("Hidden").tag("invisible")
1170                    Text("Shown as usual").tag("nil")
1171                }
1172            }
1173            Section {
1174                Toggle("Show events from Calendar", isOn: $calendarEvents)
1175                    .disabled(!ProAccess.shared.isUnlocked && !calendarEvents)
1176                    .help(ProAccess.shared.isUnlocked ? "" : "Needs orgstar+")
1177                if calendarEvents {
1178                    choices(calendars, empty: CalendarEvents.isAuthorized ? "No calendars." : "Allow orgstar to read your calendars in System Settings ▸ Privacy & Security ▸ Calendars.", setting: $calendarEventCalendars)
1179                }
1180            } footer: {
1181                Text("Events show in the agenda; double-click one to open it in Calendar, or choose Edit Event… in its context menu. New calendars show while every calendar is checked.")
1182                    .settingsFooter()
1183            }
1184            .task(id: calendarEvents) {
1185                let allowed = calendarEvents ? await CalendarAccess.events.requestAccess() : false
1186                calendars = allowed ? CalendarAccess.events.calendars() : []
1187            }
1188            Section {
1189                Toggle("Show reminders from Reminders", isOn: $agendaReminders)
1190                    .disabled(!ProAccess.shared.isUnlocked && !agendaReminders)
1191                    .help(ProAccess.shared.isUnlocked ? "" : "Needs orgstar+")
1192                if agendaReminders {
1193                    choices(reminderLists, empty: ReminderLists.isAuthorized ? "No lists." : "Allow orgstar to read your reminders in System Settings ▸ Privacy & Security ▸ Reminders.", setting: $agendaReminderLists)
1194                }
1195            } footer: {
1196                Text("Incomplete reminders with a due date show in the agenda read-only, overdue ones under today; double-click one to open it in Reminders.")
1197                    .settingsFooter()
1198            }
1199            .task(id: agendaReminders) {
1200                let allowed = agendaReminders ? await CalendarAccess.reminders.requestAccess() : false
1201                reminderLists = allowed ? CalendarAccess.reminders.lists() : []
1202            }
1203            Section {
1204                Toggle("Notify before timed agenda entries", isOn: $reminders)
1205                Stepper("\(reminderLead) minutes before", value: $reminderLead, in: 0...120)
1206                    .disabled(!reminders)
1207            } footer: {
1208                Text("An entry's APPT_WARNTIME property overrides the lead time.")
1209                    .settingsFooter()
1210            }
1211            Section {
1212                Toggle("Ask what to do with idle time while clocked in", isOn: Binding {
1213                    clockIdleTime > 0
1214                } set: { on in
1215                    clockIdleTime = on ? 15 : 0
1216                })
1217                Stepper("After \(max(clockIdleTime, 1)) minutes without keyboard or mouse input", value: $clockIdleTime, in: 1...240)
1218                    .disabled(clockIdleTime == 0)
1219                Stepper("Remember \(clockHistoryLength) recently clocked entries", value: $clockHistoryLength, in: 1...35)
1220            } footer: {
1221                Text("org-clock-idle-time and org-clock-history-length. Org ▸ Clock lists the recent entries.")
1222                    .settingsFooter()
1223            }
1224        }
1225        .formStyle(.grouped)
1226        .frame(height: 560)
1227    }
1228
1229    /// A toggle per calendar or reminder list, with its color; `empty` when there are none.
1230    @ViewBuilder
1231    private func choices(_ calendars: [(id: String, title: String, color: RGBA?)], empty: LocalizedStringKey, setting: Binding<String>) -> some View {
1232        if calendars.isEmpty {
1233            Text(empty)
1234                .foregroundStyle(.secondary)
1235        }
1236        ForEach(calendars, id: \.id) { calendar in
1237            Toggle(isOn: chosen(calendar, among: calendars, setting: setting)) {
1238                HStack(spacing: 6) {
1239                    Circle()
1240                        .fill(calendar.color.map { Color(.sRGB, red: $0.red, green: $0.green, blue: $0.blue, opacity: $0.alpha) } ?? .secondary)
1241                        .frame(width: 8, height: 8)
1242                    Text(calendar.title)
1243                }
1244            }
1245        }
1246    }
1247
1248    /// `calendar-event-calendars` and `agenda-reminder-lists`: empty for every calendar or
1249    /// list, else the titles checked.
1250    private func chosen(
1251        _ calendar: (id: String, title: String, color: RGBA?), among calendars: [(id: String, title: String, color: RGBA?)], setting: Binding<String>
1252    ) -> Binding<Bool> {
1253        let chosen = setting.wrappedValue.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
1254        return Binding {
1255            CalendarEvents.chooses(id: calendar.id, title: calendar.title, chosen: chosen)
1256        } set: { on in
1257            var titles = calendars.map(\.title).filter { title in
1258                chosen.isEmpty || chosen.contains(title) || chosen.contains(calendars.first { $0.title == title }?.id ?? "")
1259            }
1260            titles.removeAll { $0 == calendar.title }
1261            if on { titles.append(calendar.title) }
1262            // An empty list means every calendar; turning events off hides them all.
1263            guard !titles.isEmpty else { return }
1264            setting.wrappedValue = Set(titles) == Set(calendars.map(\.title)) ? "" : titles.joined(separator: ", ")
1265        }
1266    }
1267
1268    private var capture: some View {
1269        Form {
1270            Section {
1271                Toggle("⌃⌥Space opens Capture from any app", isOn: $globalCapture)
1272            } footer: {
1273                Text("Templates go in \(CaptureTemplates.userFile.path).")
1274                    .settingsFooter()
1275            }
1276        }
1277        .formStyle(.grouped)
1278        .frame(height: 160)
1279    }
1280}
1281
1282extension Text {
1283    func settingsFooter() -> some View {
1284        font(.caption)
1285            .foregroundStyle(.secondary)
1286            .textSelection(.enabled)
1287            .frame(maxWidth: .infinity, alignment: .leading)
1288    }
1289}
Keyboard shortcuts

Global

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

Repository & editor

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