Sources/Orgstar/OrgstarApp.swift

fc3ddfcd5858fab2b88399e3df1ce76f3213a7c9
orgstar/Sources/Orgstar/OrgstarApp.swift

1266 lines · 61313 bytes

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