Sources/Orgstar/OrgstarApp.swift

0dc8dea033dd64cad6c9b4130124d1c229454342
orgstar/Sources/Orgstar/OrgstarApp.swift

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