Sources/Orgstar/OrgstarApp.swift

29b770d6b2f9edcc6607ab4a46db6c659dd12c1d
orgstar/Sources/Orgstar/OrgstarApp.swift

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