Sources/Orgstar/OrgstarApp.swift

fbc792eb21866a31f8edcffd23f5105df3be2348
orgstar/Sources/Orgstar/OrgstarApp.swift

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