Sources/Orgstar/OrgstarApp.swift

ab61bf091480c1b3b815f8ff8e3d8297e2ca45b7
orgstar/Sources/Orgstar/OrgstarApp.swift

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