Sources/Orgstar/OrgstarApp.swift

5b5584bafaafd3d627ecb2778987cef0e743de9c
orgstar/Sources/Orgstar/OrgstarApp.swift

1291 lines · 62556 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                Button("Lint File") { commands.run("app.lint") }
 533                    .disabled(!FileLint.applies(to: session.path))
 534            }
 535            CommandGroup(replacing: .saveItem) {
 536                Button("Close Buffer") {
 537                    // ⌘W closes the buffer in the main window, and other windows themselves.
 538                    if let key = NSApp.keyWindow, key.identifier?.rawValue.contains("main") != true {
 539                        key.performClose(nil)
 540                    } else {
 541                        commands.run("app.buffer.kill")
 542                    }
 543                }
 544                .keyboardShortcut("w")
 545                Button("Close Window") { NSApp.keyWindow?.performClose(nil) }
 546                    .keyboardShortcut("w", modifiers: [.command, .shift])
 547                Divider()
 548                Button("Save") {
 549                    if !session.save(), session.conflict != nil { commands.showingConflict = true }
 550                }
 551                .keyboardShortcut("s")
 552                .disabled(session.path == nil || session.isReadOnly)
 553                Button("Save All") { commands.run("app.save-all") }
 554                    .keyboardShortcut("s", modifiers: [.command, .option])
 555                    .disabled(session.dirtyPaths.isEmpty)
 556            }
 557            CommandGroup(after: .sidebar) {
 558                Button("Split Pane Below") { commands.run("app.split-below") }
 559                    .keyboardShortcut("2", modifiers: [.command, .control])
 560                Button("Split Pane Right") { commands.run("app.split-right") }
 561                    .keyboardShortcut("3", modifiers: [.command, .control])
 562                Button("Close Pane") { commands.run("app.pane-close") }
 563                    .keyboardShortcut("0", modifiers: [.command, .control])
 564                Button("Close Other Panes") { commands.run("app.pane-only") }
 565                    .keyboardShortcut("1", modifiers: [.command, .control])
 566                Button("Next Pane") { commands.run("app.pane-next") }
 567                    .keyboardShortcut("`", modifiers: [.command, .option])
 568                Divider()
 569                ViewMenuToggles(commands: commands)
 570                Divider()
 571                Button("Messages") { commands.run("app.messages") }
 572            }
 573            CommandGroup(after: .pasteboard) {
 574                Divider()
 575                FindMenu(commands: commands)
 576                MacroMenu(commands: commands)
 577            }
 578            CommandGroup(after: .textEditing) {
 579                Button("Cancel Running Task") { commands.run("app.babel.cancel") }
 580                    .keyboardShortcut(".")
 581                    .disabled(!session.isRunningBabel && commands.emacsTask == nil)
 582                Button("Search Notes") { commands.focusSearch = true }
 583                    .keyboardShortcut("f", modifiers: [.command, .shift])
 584            }
 585            CommandGroup(before: .windowList) {
 586                AgendaMenuItem()
 587                Divider()
 588                Button("Switch to Buffer…") { commands.run("app.buffer.switch") }
 589                Button("Next Buffer") { commands.run("app.buffer.next") }
 590                    .keyboardShortcut("]", modifiers: [.command, .shift])
 591                Button("Previous Buffer") { commands.run("app.buffer.previous") }
 592                    .keyboardShortcut("[", modifiers: [.command, .shift])
 593                Divider()
 594            }
 595            CommandGroup(after: .newItem) {
 596                Button("Capture…") { commands.run("app.capture") }
 597                    .keyboardShortcut("n", modifiers: [.command, .shift])
 598                Button("New File from Template…") { commands.run("app.new-file-from-template") }
 599                Button("New Window") { commands.run("app.window-new") }
 600                    .keyboardShortcut("n", modifiers: [.command, .option])
 601            }
 602        }
 603        .commands {
 604            CommandMenu("Org") {
 605                ClockMenu(commands: commands, clock: clock)
 606                Divider()
 607                OrgMenuItems(commands: commands)
 608            }
 609        }
 610        .commands {
 611            CommandGroup(after: .appSettings) {
 612                Button("Edit Config File") { commands.jump(path: UserConfig.configFile.path, offset: 0) }
 613                    .keyboardShortcut(",", modifiers: [.command, .option])
 614            }
 615            #if !APPSTORE
 616            CommandGroup(after: .appInfo) {
 617                CheckForUpdatesItem(updates: delegate.updates)
 618            }
 619            #endif
 620            CommandGroup(replacing: .help) {
 621                Button("orgstar Manual") { NSWorkspace.shared.open(Manual.home) }
 622                Button("Keys") { NSWorkspace.shared.open(Manual.keys) }
 623                Divider()
 624                Button("What's New in orgstar") { commands.whatsNew = WhatsNew.releases.first }
 625                    .disabled(!commands.mainWindowOpen)
 626            }
 627        }
 628        Settings {
 629            #if APPSTORE
 630            SettingsView(commands: commands, workspace: try? workspace.get())
 631            #else
 632            SettingsView(commands: commands, workspace: try? workspace.get(), updates: delegate.updates)
 633            #endif
 634        }
 635    }
 636}
 637
 638/// The Org menu: every org command and the app's commands for entries and notes, in submenus by
 639/// subject, with the keys that run them in the current keymap.
 640struct OrgMenuItems: View {
 641    let commands: AppCommands
 642
 643    /// Submenus and the command id prefixes they hold, in menu order. A command goes in the
 644    /// first submenu with a prefix it starts with.
 645    static let groups: [(title: LocalizedStringKey, prefixes: [String])] = [
 646        ("Visibility", ["org.cycle", "org.fold.", "org.narrow.", "org.widen", "org.sparse-tree", "org.toggle-inline-images", "org.latex-preview"]),
 647        ("Headings", ["org.heading.", "org.subtree.", "org.element.", "org.goto", "org.sort", "org.archive.", "app.refile", "app.archive"]),
 648        ("TODO and Tags", ["org.todo.", "org.priority.", "org.tags.", "org.effort.", "app.rename-"]),
 649        ("Properties and Columns", ["org.property.", "org.columns", "org.drawer."]),
 650        ("Dates and Timers", ["org.schedule", "org.deadline", "org.timestamp.", "org.timer."]),
 651        ("Lists", ["org.item.", "org.checkbox."]),
 652        ("Tables", ["org.table", "app.table-", "app.plot"]),
 653        ("Links and Footnotes", ["org.link.", "org.id.", "org.footnote."]),
 654        ("Blocks", ["org.babel.", "org.structure-template", "org.edit-special", "org.dblock.", "org.clock.report", "org.denote."]),
 655        ("Text", ["org.emphasize", "org.fill-"]),
 656        ("Attachments", ["app.attach."]),
 657        ("Notes", ["app.dailies.", "app.node."]),
 658        ("Encryption", ["app.crypt."]),
 659    ]
 660
 661    private static func group(of id: String) -> Int? {
 662        groups.firstIndex { $0.prefixes.contains { id.hasPrefix($0) } }
 663    }
 664
 665    private static let shown = EditorCommands.all.filter { ($0.id.hasPrefix("org.") || group(of: $0.id) != nil) && !hiddenCommandIDs.contains($0.id) }
 666
 667    var body: some View {
 668        // Commands that fit no subject, such as Act at Point, come first.
 669        ForEach(Self.shown.filter { Self.group(of: $0.id) == nil }, id: \.id) { item($0) }
 670        Divider()
 671        ForEach(Self.groups.indices, id: \.self) { index in
 672            Menu(Self.groups[index].title) {
 673                ForEach(Self.shown.filter { Self.group(of: $0.id) == index }, id: \.id) { item($0) }
 674            }
 675        }
 676    }
 677
 678    private func item(_ command: EditorCommand) -> some View {
 679        Button {
 680            if command.id.hasPrefix("org.") { commands.editor?.run(command.id) } else { commands.run(command.id) }
 681        } label: {
 682            Text(command.localizedTitle)
 683            if let keys = commands.keyLabel(for: command.id) { Text(keys) }
 684        }
 685        .disabled(command.id.hasPrefix("org.") && commands.editor == nil)
 686    }
 687}
 688
 689/// The user manual, as `scripts/publish-docs.sh` publishes it.
 690enum Manual {
 691    static let home = URL(string: "https://files.krz.sh/orgstar/")!
 692    /// The key reference, with every preset's keys.
 693    static let keys = URL(string: "https://files.krz.sh/orgstar/guide/03-keys.html#key-reference")!
 694}
 695
 696/// View ▸ the panes and the focused editor's modes, checked while on.
 697struct ViewMenuToggles: View {
 698    let commands: AppCommands
 699    @AppStorage("backlinksShown") private var backlinksShown = true
 700    @AppStorage("inspectorShown") private var inspectorShown = false
 701
 702    var body: some View {
 703        let outline = commands.outlineShown
 704        let editor = commands.editor
 705        // A key that switches an editor mode shows a message, so the checks follow it.
 706        let _ = commands.message
 707        Toggle("Show Outline", isOn: Binding(get: { outline }, set: { _ in commands.run("app.toggle-outline") }))
 708            .keyboardShortcut("o", modifiers: [.command, .option])
 709        Toggle("Show Backlinks", isOn: $backlinksShown)
 710        Toggle("Show Inspector", isOn: $inspectorShown)
 711            .keyboardShortcut("i", modifiers: [.command, .option])
 712        MarkupToggle()
 713        editorToggle("Truncate Long Lines", "editor.toggle-truncate-lines", editor?.truncatesLines)
 714        editorToggle("Auto Fill", "editor.toggle-auto-fill", editor?.autoFills)
 715        editorToggle("Check Spelling While Typing", "editor.toggle-spell-check", editor?.spellChecking)
 716    }
 717
 718    private func editorToggle(_ title: LocalizedStringKey, _ id: String, _ on: Bool?) -> some View {
 719        Toggle(title, isOn: Binding(get: { on ?? false }, set: { _ in commands.editor?.run(id) }))
 720            .disabled(on == nil)
 721    }
 722}
 723
 724/// View ▸ Show Markup (link brackets and targets, emphasis markers) and Show Line Numbers.
 725struct MarkupToggle: View {
 726    @AppStorage("showTabBar") private var showTabBar = false
 727    @AppStorage("showMarkup") private var showMarkup = false
 728    @AppStorage("showLineNumbers") private var showLineNumbers = false
 729    @AppStorage("lineNumbersType") private var lineNumbersType = "t"
 730
 731    var body: some View {
 732        Toggle("Show Markup", isOn: $showMarkup)
 733            .keyboardShortcut("m", modifiers: [.command, .shift])
 734        Toggle("Show Line Numbers", isOn: $showLineNumbers)
 735            .keyboardShortcut("l", modifiers: [.command, .shift])
 736        Picker("Line Numbers", selection: $lineNumbersType) {
 737            Text("Absolute").tag("t")
 738            Text("Relative").tag("relative")
 739            Text("Visual").tag("visual")
 740        }
 741        Toggle("Show Tab Bar", isOn: $showTabBar)
 742    }
 743}
 744
 745/// Edit ▸ Find: the editor's find bar.
 746struct FindMenu: View {
 747    let commands: AppCommands
 748
 749    var body: some View {
 750        Menu("Find") {
 751            item("Find…", "edit.find", "f")
 752            item("Find and Replace…", "edit.replace", "f", [.command, .option])
 753            item("Find Next", "edit.find-next", "g")
 754            item("Find Previous", "edit.find-previous", "g", [.command, .shift])
 755            item("Use Selection for Find", "edit.use-selection-for-find", "e")
 756            Divider()
 757            Button("Replace in Files…") { commands.run("app.replace-in-files") }
 758                .keyboardShortcut("f", modifiers: [.command, .option, .shift])
 759        }
 760    }
 761
 762    private func item(_ title: String, _ id: String, _ key: KeyEquivalent, _ modifiers: EventModifiers = .command) -> some View {
 763        Button(title) { commands.editor?.run(id) }
 764            .keyboardShortcut(key, modifiers: modifiers)
 765            .disabled(commands.editor == nil)
 766    }
 767}
 768
 769/// Edit ▸ Macros: keyboard macros, with the keys that run them in the current keymap.
 770struct MacroMenu: View {
 771    let commands: AppCommands
 772
 773    var body: some View {
 774        Menu("Macros") {
 775            item("Start Recording", "macro.start")
 776            item("Stop Recording", "macro.end")
 777            item("Run Last Macro", "macro.call")
 778            Divider()
 779            item("Name Last Macro…", "macro.name")
 780            item("Run Macro…", "macro.run")
 781        }
 782    }
 783
 784    private func item(_ title: LocalizedStringKey, _ id: String) -> some View {
 785        Button {
 786            commands.editor?.run(id)
 787        } label: {
 788            Text(title)
 789            if let keys = commands.keyLabel(for: id) { Text(keys) }
 790        }
 791        .disabled(commands.editor == nil)
 792    }
 793}
 794
 795/// Window ▸ Agenda.
 796struct AgendaMenuItem: View {
 797    @Environment(\.openWindow) private var openWindow
 798
 799    var body: some View {
 800        Button("Agenda") { openWindow(id: "agenda") }
 801            .keyboardShortcut("a", modifiers: [.command, .shift])
 802        Button("Board") { openWindow(id: "board") }
 803            .keyboardShortcut("b", modifiers: [.command, .shift])
 804        Button("Graph") { if ProAccess.shared.allows(.roam) { openWindow(id: "graph") } }
 805    }
 806}
 807
 808struct SettingsView: View {
 809    let commands: AppCommands
 810    let workspace: WorkspaceModel?
 811    #if !APPSTORE
 812    let updates: Updates
 813    #endif
 814    @State private var importing = false
 815    #if APPSTORE
 816    @State private var configFolder = UserConfig.directoryOverride
 817    #endif
 818    @Environment(\.openWindow) private var openWindow
 819    @AppStorage("saveMode") private var saveMode = SaveMode.automatic
 820    @AppStorage("keymap") private var preset = KeymapPreset.emacs
 821    @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
 822    @AppStorage("tagsColumn") private var tagsColumn = -77
 823    @AppStorage("headingAfterSubtree") private var headingAfterSubtree = false
 824    @AppStorage("splitLine") private var splitLine = false
 825    @AppStorage("alphabeticalLists") private var alphabeticalLists = true
 826    @AppStorage("fillColumn") private var fillColumn = 80
 827    @AppStorage("hiddenMarkers") private var hiddenMarkers = true
 828    @AppStorage("prettyEntities") private var prettyEntities = true
 829    @AppStorage("startupTruncated") private var startupTruncated = false
 830    @AppStorage("todoKeywords") private var todoKeywords = Preferences.defaultTodoKeywords
 831    @AppStorage("logDone") private var logDone = "nil"
 832    @AppStorage("logIntoDrawer") private var logIntoDrawer = ""
 833    @AppStorage("useSpeedCommands") private var useSpeedCommands = false
 834    @AppStorage("spellCheck") private var spellCheck = false
 835    @AppStorage("completionAuto") private var completionAuto = "preset"
 836    @AppStorage("completionAutoDelay") private var completionAutoDelay = 400
 837    @AppStorage("completionAutoPrefix") private var completionAutoPrefix = 2
 838    @AppStorage("completionStyle") private var completionStyle = "preset"
 839    @AppStorage("completionWords") private var completionWords = false
 840    @AppStorage("enforceTodoDependencies") private var enforceTodoDependencies = false
 841    @AppStorage("enforceTodoCheckboxDependencies") private var enforceTodoCheckboxDependencies = false
 842    @AppStorage("agendaSpan") private var agendaSpan = 10
 843    @AppStorage("agendaStartOffset") private var agendaStartOffset = 0
 844    @AppStorage("agendaSubfolders") private var agendaSubfolders = false
 845    @AppStorage("agendaShowAllDates") private var agendaShowAllDates = false
 846    @AppStorage("habitsOnlyForToday") private var habitsOnlyForToday = true
 847    @AppStorage("agendaDimBlockedTasks") private var agendaDimBlockedTasks = "t"
 848    @AppStorage("calendarEvents") private var calendarEvents = false
 849    @AppStorage("calendarEventCalendars") private var calendarEventCalendars = ""
 850    @State private var calendars: [(id: String, title: String, color: RGBA?)] = []
 851    @AppStorage("agendaReminders") private var agendaReminders = false
 852    @AppStorage("agendaReminderLists") private var agendaReminderLists = ""
 853    @State private var reminderLists: [(id: String, title: String, color: RGBA?)] = []
 854    @AppStorage("reminders") private var reminders = true
 855    @AppStorage("reminderLead") private var reminderLead = 12
 856    @AppStorage("clockIdleTime") private var clockIdleTime = 0
 857    @AppStorage("clockHistoryLength") private var clockHistoryLength = 5
 858    @AppStorage("globalCapture") private var globalCapture = true
 859    @AppStorage("menuBarItem") private var menuBarItem = false
 860    @AppStorage("settingsTab") private var tab = "general"
 861    @AppStorage("showHiddenFiles") private var showHiddenFiles = true
 862    @AppStorage("themeFont") private var themeFont = ""
 863    @AppStorage("themeBodyFont") private var themeBodyFont = ""
 864    @AppStorage("themeFontSize") private var themeFontSize = 13
 865    @AppStorage("themeLineSpacing") private var themeLineSpacing = 2
 866    @AppStorage("themeTextWidth") private var themeTextWidth = 0
 867    @AppStorage("themeHeadingStep") private var themeHeadingStep = 1
 868
 869    /// Installed font families that aren't monospaced, for body text.
 870    private static let proportionalFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in
 871        NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == false
 872    }
 873
 874    /// Installed monospaced font families.
 875    private static let monospacedFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in
 876        NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == true
 877    }
 878
 879    var body: some View {
 880        TabView(selection: $tab) {
 881            Tab("General", systemImage: "gearshape", value: "general") { general }
 882            Tab("Editing", systemImage: "text.alignleft", value: "editing") { editing }
 883            Tab("Appearance", systemImage: "paintpalette", value: "appearance") { appearance }
 884            Tab("Agenda", systemImage: "calendar", value: "agenda") { agenda }
 885            Tab("Capture", systemImage: "tray.and.arrow.down", value: "capture") { capture }
 886            #if !APPSTORE
 887            Tab(value: "git") { GitSettingsForm(workspace: workspace) } label: {
 888                Label { Text("Git", tableName: "DeveloperID") } icon: { Image(systemName: "arrow.triangle.branch") }
 889            }
 890            #endif
 891            #if APPSTORE
 892            Tab("orgstar+", systemImage: "star", value: "pro") { StoreForm() }
 893            #else
 894            Tab("orgstar+", systemImage: "star", value: "pro") { LicenseForm() }
 895            #endif
 896        }
 897        .frame(width: 600)
 898    }
 899
 900    private func editConfig() {
 901        ConfigSync.shared.start()
 902        openWindow(id: "main")
 903        commands.jump(path: UserConfig.configFile.path, offset: 0)
 904    }
 905
 906    #if APPSTORE
 907    /// A folder outside the app's container, such as `~/.config/orgstar` kept with dotfiles.
 908    private func chooseConfigFolder() {
 909        let panel = NSOpenPanel()
 910        panel.canChooseFiles = false
 911        panel.canChooseDirectories = true
 912        panel.canCreateDirectories = true
 913        panel.directoryURL = configFolder ?? ConfigFolder.suggested
 914        panel.message = String(localized: "Choose the folder for config.toml and orgstar's other configuration files.", comment: "Choose Configuration Folder panel")
 915        guard panel.runModal() == .OK, let url = panel.url else { return }
 916        if !ConfigFolder.set(url) {
 917            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"),
 918                             String(localized: "Access lasts until orgstar quits.", comment: "Alert when a folder grant or the configuration folder can't be saved"))
 919        }
 920        useConfigFolder(url)
 921    }
 922
 923    /// Reads and writes the configuration in `url`, or with nil in the default folder.
 924    private func useConfigFolder(_ url: URL?) {
 925        if url == nil { ConfigFolder.clear() }
 926        UserConfig.directoryOverride = url
 927        configFolder = url
 928        ConfigSync.shared.move(to: UserConfig.configFile)
 929    }
 930    #endif
 931
 932    private var general: some View {
 933        Form {
 934            Section {
 935                LabeledContent("config.toml") {
 936                    HStack {
 937                        Button("Edit in orgstar") { editConfig() }
 938                        Button("Open with Default App") { NSWorkspace.shared.open(UserConfig.configFile) }
 939                        Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([UserConfig.configFile]) }
 940                    }
 941                }
 942                #if APPSTORE
 943                LabeledContent("Folder") {
 944                    HStack {
 945                        Button("Choose Configuration Folder…") { chooseConfigFolder() }
 946                        if configFolder != nil { Button("Use Default Folder") { useConfigFolder(nil) } }
 947                    }
 948                }
 949                #endif
 950                LabeledContent("Emacs") {
 951                    Button("Import from Emacs…") { importing = true }
 952                }
 953            } footer: {
 954                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.")
 955                    .settingsFooter()
 956            }
 957            #if !APPSTORE
 958            if updates.canCheck {
 959                Section {
 960                    Toggle(isOn: Binding(get: { updates.automatically }, set: { updates.automatically = $0 })) { Text("Check for updates automatically", tableName: "DeveloperID") }
 961                } footer: {
 962                    Text("Once a day, from the app's own feed. orgstar ▸ Check for Updates… checks now.", tableName: "DeveloperID")
 963                        .settingsFooter()
 964                }
 965            }
 966            #endif
 967            Section {
 968                Picker("Save files", selection: $saveMode) {
 969                    Text("Automatically, when typing stops").tag(SaveMode.automatic)
 970                    Text("Only with File ▸ Save (⌘S)").tag(SaveMode.explicit)
 971                }
 972                .pickerStyle(.radioGroup)
 973            }
 974            Section {
 975                Picker("Keys", selection: $preset) {
 976                    ForEach(KeymapPreset.allCases, id: \.self) { Text($0.title).tag($0) }
 977                }
 978                Toggle("Show hidden files and folders", isOn: $showHiddenFiles)
 979                Toggle("Keep orgstar in the menu bar", isOn: $menuBarItem)
 980                    .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.")
 981                Picker("Option as Meta", selection: $optionAsMeta) {
 982                    Text("Left Option").tag(OptionAsMeta.left.rawValue)
 983                    Text("Right Option").tag(OptionAsMeta.right.rawValue)
 984                    Text("Both").tag(OptionAsMeta([.left, .right]).rawValue)
 985                    Text("Neither").tag(0)
 986                }
 987            } footer: {
 988                Text("Your own bindings go in \(KeymapLoader.userFile.path), on top of the preset.")
 989                    .settingsFooter()
 990            }
 991        }
 992        .formStyle(.grouped)
 993        .frame(height: 330)
 994        .sheet(isPresented: $importing) { EmacsImportView(workspace: workspace) }
 995    }
 996
 997    private var editing: some View {
 998        Form {
 999            Section {
1000                Picker("Tags", selection: $tagsColumn) {
1001                    Text("Aligned to end at column 77").tag(-77)
1002                    Text("One space after the title").tag(0)
1003                }
1004                .help(Text(verbatim: "org-tags-column"))
1005                Toggle(isOn: $headingAfterSubtree) { keyed("New headings go after the subtree", "org.heading.insert") }
1006                    .help(Text(verbatim: "org-insert-heading-respect-content"))
1007                Toggle(isOn: $splitLine) { keyed("New headings and items split the line at the caret", "org.heading.insert") }
1008                    .help(Text(verbatim: "org-M-RET-may-split-line"))
1009                Toggle("Lists can use letters (a. b. c.)", isOn: $alphabeticalLists)
1010                    .help(Text(verbatim: "org-list-allow-alphabetical"))
1011                Stepper(value: $fillColumn, in: 40...200) { keyed("Fill Paragraph wraps lines at column \(fillColumn)", "org.fill-paragraph") }
1012                    .help(Text(verbatim: "fill-column"))
1013            }
1014            Section {
1015                Toggle("Long lines run off the edge instead of wrapping", isOn: $startupTruncated)
1016                    .help(Text(verbatim: "org-startup-truncated"))
1017            } footer: {
1018                Text("Applies to files as they open. View ▸ Truncate Long Lines switches the current file.")
1019                    .settingsFooter()
1020            }
1021            Section {
1022                Toggle("Emacs hides emphasis markers", isOn: $hiddenMarkers)
1023                    .help(Text(verbatim: "org-hide-emphasis-markers"))
1024                Toggle("Emacs shows entities as characters", isOn: $prettyEntities)
1025                    .help(Text(verbatim: "org-pretty-entities"))
1026            } footer: {
1027                Text("Tags, tables and Fill Paragraph measure text as your Emacs displays it, so both write the same file.")
1028                    .settingsFooter()
1029            }
1030            Section {
1031                TextField("Default TODO keywords", text: $todoKeywords, axis: .vertical)
1032            } footer: {
1033                Text("For files without #+TODO, in #+TODO syntax, one sequence per line. Takes effect when orgstar restarts.")
1034                    .settingsFooter()
1035            }
1036            Section {
1037                Toggle("Entries can't be done before their TODO children", isOn: $enforceTodoDependencies)
1038                    .help(Text(verbatim: "org-enforce-todo-dependencies"))
1039                Toggle("Entries can't be done with unchecked boxes", isOn: $enforceTodoCheckboxDependencies)
1040                    .help(Text(verbatim: "org-enforce-todo-checkbox-dependencies"))
1041            } footer: {
1042                Text("Under a parent with the ORDERED property (Org ▸ Properties and Columns ▸ Toggle ORDERED Property), TODO children are also done in order.")
1043                    .settingsFooter()
1044            }
1045            Section {
1046                Picker("When an entry is done", selection: $logDone) {
1047                    Text("Record nothing").tag("nil")
1048                    Text("Record the time, as CLOSED").tag("time")
1049                    Text("Record the time and ask for a note").tag("note")
1050                }
1051                .help(Text(verbatim: "org-log-done"))
1052                Toggle("State notes go in a LOGBOOK drawer", isOn: logIntoDrawerOn)
1053                    .help(Text(verbatim: "org-log-into-drawer"))
1054            } footer: {
1055                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.")
1056                    .settingsFooter()
1057            }
1058            Section {
1059                Toggle("Speed keys: single letters at the start of a heading line run commands", isOn: $useSpeedCommands)
1060                    .help(Text(verbatim: "org-use-speed-commands"))
1061                Toggle("Check spelling while typing", isOn: $spellCheck)
1062                    .help(Text(verbatim: "spell-check"))
1063            } footer: {
1064                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.")
1065                    .settingsFooter()
1066            }
1067            Section {
1068                Picker("Completion list opens", selection: $completionAuto) {
1069                    Text("As the keys do (by itself with Doom)").tag("preset")
1070                    Text("By itself as you type").tag("on")
1071                    Text("Only with a key").tag("off")
1072                }
1073                .help(Text(verbatim: "completion-auto"))
1074                Stepper("After a pause of \(completionAutoDelay) ms", value: $completionAutoDelay, in: 0...2000, step: 50)
1075                    .help(Text(verbatim: "completion-auto-delay"))
1076                Stepper("Once \(completionAutoPrefix) characters are typed", value: $completionAutoPrefix, in: 1...10)
1077                    .help(Text(verbatim: "completion-auto-prefix"))
1078                Picker("Candidates", selection: $completionStyle) {
1079                    Text("As the keys do (letters in order with Doom)").tag("preset")
1080                    Text("Start with what's typed").tag("prefix")
1081                    Text("Have its letters in order, best first").tag("fuzzy")
1082                }
1083                .help(Text(verbatim: "completion-style"))
1084                Toggle("The list offers words from open files and folders", isOn: $completionWords)
1085                    .help(Text(verbatim: "completion-words"))
1086            } header: {
1087                Text("Completion")
1088            } footer: {
1089                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.")
1090                    .settingsFooter()
1091            }
1092        }
1093        .formStyle(.grouped)
1094        .frame(height: 860)
1095    }
1096
1097    /// `label`, then the keys that run `command` in the current preset, if any.
1098    private func keyed(_ label: LocalizedStringKey, _ command: String) -> some View {
1099        HStack(spacing: 6) {
1100            Text(label)
1101            if let keys = commands.keyLabel(for: command) {
1102                Text(verbatim: keys).font(.system(.body, design: .monospaced)).foregroundStyle(.secondary)
1103            }
1104        }
1105    }
1106
1107    /// `org-log-into-drawer` as a switch: on is "LOGBOOK" (Emacs's t); a drawer name of its own counts as on.
1108    private var logIntoDrawerOn: Binding<Bool> {
1109        Binding(get: { !logIntoDrawer.isEmpty }, set: { logIntoDrawer = $0 ? "LOGBOOK" : "" })
1110    }
1111
1112    private var appearance: some View {
1113        Form {
1114            ThemePickerSection()
1115            AppIconSection()
1116            Section {
1117                Picker("Font", selection: $themeFont) {
1118                    Text("System monospaced").tag("")
1119                    Divider()
1120                    ForEach(Self.monospacedFamilies, id: \.self) { Text($0).tag($0) }
1121                    if !themeFont.isEmpty, !Self.monospacedFamilies.contains(themeFont) { Text(themeFont).tag(themeFont) }
1122                }
1123                Picker("Body font", selection: $themeBodyFont) {
1124                    Text("Same as Font").tag("")
1125                    Text("System").tag("system")
1126                    Divider()
1127                    ForEach(Self.proportionalFamilies, id: \.self) { Text($0).tag($0) }
1128                    if !["", "system"].contains(themeBodyFont), !Self.proportionalFamilies.contains(themeBodyFont) { Text(themeBodyFont).tag(themeBodyFont) }
1129                }
1130                Stepper("Size: \(themeFontSize) pt", value: $themeFontSize, in: 8...36)
1131                Stepper("Line spacing: \(themeLineSpacing) pt", value: $themeLineSpacing, in: 0...16)
1132                Picker("Text width", selection: $themeTextWidth) {
1133                    Text("Whole editor").tag(0)
1134                    ForEach([60, 70, 80, 90, 100, 120], id: \.self) { Text("\($0) columns").tag($0) }
1135                    if ![0, 60, 70, 80, 90, 100, 120].contains(themeTextWidth) { Text("\(themeTextWidth) columns").tag(themeTextWidth) }
1136                }
1137                Stepper("Headings grow by \(themeHeadingStep) pt a level", value: $themeHeadingStep, in: 0...8)
1138            } footer: {
1139                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.")
1140                    .settingsFooter()
1141            }
1142            Section {
1143                LabeledContent("Colors") {
1144                    HStack {
1145                        Button("Edit in config.toml") { editConfig() }
1146                        Button("Show Default Theme") {
1147                            openWindow(id: "main")
1148                            commands.jump(path: UserConfig.directory.appendingPathComponent("default-theme.toml").path, offset: 0)
1149                        }
1150                    }
1151                }
1152            } footer: {
1153                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.")
1154                    .settingsFooter()
1155            }
1156        }
1157        .formStyle(.grouped)
1158        .frame(height: 620)
1159    }
1160
1161    private var agenda: some View {
1162        Form {
1163            Section {
1164                Stepper("Agenda shows \(agendaSpan) days", value: $agendaSpan, in: 1...366)
1165                Stepper(agendaStartOffset == 0 ? "Agenda starts today" : "Agenda starts \(-agendaStartOffset) days before today", value: $agendaStartOffset, in: -14...0)
1166                Toggle("Include files in subfolders", isOn: $agendaSubfolders)
1167                Toggle("Show days without entries", isOn: $agendaShowAllDates)
1168                Toggle("Habits only today", isOn: $habitsOnlyForToday)
1169                Picker("Blocked entries", selection: $agendaDimBlockedTasks) {
1170                    Text("Dimmed").tag("t")
1171                    Text("Hidden").tag("invisible")
1172                    Text("Shown as usual").tag("nil")
1173                }
1174            }
1175            Section {
1176                Toggle("Show events from Calendar", isOn: $calendarEvents)
1177                    .disabled(!ProAccess.shared.isUnlocked && !calendarEvents)
1178                    .help(ProAccess.shared.isUnlocked ? "" : "Needs orgstar+")
1179                if calendarEvents {
1180                    choices(calendars, empty: CalendarEvents.isAuthorized ? "No calendars." : "Allow orgstar to read your calendars in System Settings ▸ Privacy & Security ▸ Calendars.", setting: $calendarEventCalendars)
1181                }
1182            } footer: {
1183                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.")
1184                    .settingsFooter()
1185            }
1186            .task(id: calendarEvents) {
1187                let allowed = calendarEvents ? await CalendarAccess.events.requestAccess() : false
1188                calendars = allowed ? CalendarAccess.events.calendars() : []
1189            }
1190            Section {
1191                Toggle("Show reminders from Reminders", isOn: $agendaReminders)
1192                    .disabled(!ProAccess.shared.isUnlocked && !agendaReminders)
1193                    .help(ProAccess.shared.isUnlocked ? "" : "Needs orgstar+")
1194                if agendaReminders {
1195                    choices(reminderLists, empty: ReminderLists.isAuthorized ? "No lists." : "Allow orgstar to read your reminders in System Settings ▸ Privacy & Security ▸ Reminders.", setting: $agendaReminderLists)
1196                }
1197            } footer: {
1198                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.")
1199                    .settingsFooter()
1200            }
1201            .task(id: agendaReminders) {
1202                let allowed = agendaReminders ? await CalendarAccess.reminders.requestAccess() : false
1203                reminderLists = allowed ? CalendarAccess.reminders.lists() : []
1204            }
1205            Section {
1206                Toggle("Notify before timed agenda entries", isOn: $reminders)
1207                Stepper("\(reminderLead) minutes before", value: $reminderLead, in: 0...120)
1208                    .disabled(!reminders)
1209            } footer: {
1210                Text("An entry's APPT_WARNTIME property overrides the lead time.")
1211                    .settingsFooter()
1212            }
1213            Section {
1214                Toggle("Ask what to do with idle time while clocked in", isOn: Binding {
1215                    clockIdleTime > 0
1216                } set: { on in
1217                    clockIdleTime = on ? 15 : 0
1218                })
1219                Stepper("After \(max(clockIdleTime, 1)) minutes without keyboard or mouse input", value: $clockIdleTime, in: 1...240)
1220                    .disabled(clockIdleTime == 0)
1221                Stepper("Remember \(clockHistoryLength) recently clocked entries", value: $clockHistoryLength, in: 1...35)
1222            } footer: {
1223                Text("org-clock-idle-time and org-clock-history-length. Org ▸ Clock lists the recent entries.")
1224                    .settingsFooter()
1225            }
1226        }
1227        .formStyle(.grouped)
1228        .frame(height: 560)
1229    }
1230
1231    /// A toggle per calendar or reminder list, with its color; `empty` when there are none.
1232    @ViewBuilder
1233    private func choices(_ calendars: [(id: String, title: String, color: RGBA?)], empty: LocalizedStringKey, setting: Binding<String>) -> some View {
1234        if calendars.isEmpty {
1235            Text(empty)
1236                .foregroundStyle(.secondary)
1237        }
1238        ForEach(calendars, id: \.id) { calendar in
1239            Toggle(isOn: chosen(calendar, among: calendars, setting: setting)) {
1240                HStack(spacing: 6) {
1241                    Circle()
1242                        .fill(calendar.color.map { Color(.sRGB, red: $0.red, green: $0.green, blue: $0.blue, opacity: $0.alpha) } ?? .secondary)
1243                        .frame(width: 8, height: 8)
1244                    Text(calendar.title)
1245                }
1246            }
1247        }
1248    }
1249
1250    /// `calendar-event-calendars` and `agenda-reminder-lists`: empty for every calendar or
1251    /// list, else the titles checked.
1252    private func chosen(
1253        _ calendar: (id: String, title: String, color: RGBA?), among calendars: [(id: String, title: String, color: RGBA?)], setting: Binding<String>
1254    ) -> Binding<Bool> {
1255        let chosen = setting.wrappedValue.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
1256        return Binding {
1257            CalendarEvents.chooses(id: calendar.id, title: calendar.title, chosen: chosen)
1258        } set: { on in
1259            var titles = calendars.map(\.title).filter { title in
1260                chosen.isEmpty || chosen.contains(title) || chosen.contains(calendars.first { $0.title == title }?.id ?? "")
1261            }
1262            titles.removeAll { $0 == calendar.title }
1263            if on { titles.append(calendar.title) }
1264            // An empty list means every calendar; turning events off hides them all.
1265            guard !titles.isEmpty else { return }
1266            setting.wrappedValue = Set(titles) == Set(calendars.map(\.title)) ? "" : titles.joined(separator: ", ")
1267        }
1268    }
1269
1270    private var capture: some View {
1271        Form {
1272            Section {
1273                Toggle("⌃⌥Space opens Capture from any app", isOn: $globalCapture)
1274            } footer: {
1275                Text("Templates go in \(CaptureTemplates.userFile.path).")
1276                    .settingsFooter()
1277            }
1278        }
1279        .formStyle(.grouped)
1280        .frame(height: 160)
1281    }
1282}
1283
1284extension Text {
1285    func settingsFooter() -> some View {
1286        font(.caption)
1287            .foregroundStyle(.secondary)
1288            .textSelection(.enabled)
1289            .frame(maxWidth: .infinity, alignment: .leading)
1290    }
1291}
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