Sources/Orgstar/OrgstarApp.swift

b50ce164c2ff8b87dcc4256e1b3c97994dc431f8
orgstar/Sources/Orgstar/OrgstarApp.swift

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