Sources/Orgstar/OrgstarApp.swift

d6defe0dc0a9a2097c50011a25c810644b5ffaef
orgstar/Sources/Orgstar/OrgstarApp.swift

820 lines · 37632 bytes

  1import AppKit
  2import OrgApp
  3import OrgCore
  4import OrgEditorAppKit
  5import OrgPresentation
  6import SwiftUI
  7import UserNotifications
  8
  9/// Window-level requests the menu bar makes.
 10@MainActor
 11@Observable
 12final class AppCommands {
 13    var showingQuickOpen = false
 14    var showingFolderPicker = false
 15    var focusSearch = false
 16    var showingConflict = false
 17    var showingPalette = false
 18    /// A location another window asked the main window to show.
 19    private(set) var jumpRequest: (path: String, offset: Int, id: Int)?
 20    private var jumpID = 0
 21    /// Days the agenda window should show, from a followed timestamp.
 22    var agendaRequest: (start: Int, days: Int)?
 23    /// The editor with focus, for menus and the palette.
 24    var editor: OrgEditor?
 25    /// The editors and text views of every pane in every window.
 26    let store = EditorStore()
 27    /// What every editor is set up with, from the settings; the main window keeps it current.
 28    var editorSettings = EditorSettings()
 29    /// Runs work outside the text (a table recalculation in Emacs); the main window sets it.
 30    var externalHandler: ((ExternalRequest) -> Void)?
 31    /// Tags used across the workspace, for tag completion; the main window sets it.
 32    var knownTags: () -> [String] = { [] }
 33    /// The pending key prefix, and what can follow it.
 34    var pendingKeys: String?
 35    /// The editor's evil state in the Doom preset.
 36    var editorState: String?
 37    /// The keymap in use, for showing keys in menus and the palette.
 38    var keymap = KeymapPreset.emacs.keymap
 39    var modal = false
 40    /// `org-stored-links`, most recent first; kept for the session, as in Emacs.
 41    var storedLinks: [StoredLink] = []
 42
 43    /// Puts `link` first in `storedLinks` and says what happened.
 44    func storeLink(_ link: StoredLink) {
 45        show(StoredLink.add(link, to: &storedLinks))
 46    }
 47
 48    /// The keys that run `command`, as menus and the palette show them.
 49    func keyLabel(for command: String) -> String? {
 50        let labels = keymap.keyLabels(for: command, modes: modal ? ["normal", "insert"] : [nil])
 51        return labels.isEmpty ? nil : labels.joined(separator: ", ")
 52    }
 53
 54    /// The editor's selection, for the modeline.
 55    var selection = NSRange(location: 0, length: 0)
 56    var keyHints: [KeyHint] = []
 57    /// A question a command asked, answered in the echo area.
 58    private(set) var prompt: PromptRequest?
 59    /// The last message from a command or the keymap, cleared after a few seconds.
 60    private(set) var message: String?
 61    private var messageID = 0
 62
 63    func ask(_ prompt: Prompt, reply: @escaping (String?) -> Void) {
 64        self.prompt = PromptRequest(prompt: prompt, reply: reply)
 65    }
 66
 67    /// Clock questions in the echo area.
 68    var askClock: ClockModel.Ask {
 69        { [self] prompt in
 70            await withCheckedContinuation { continuation in
 71                ask(prompt) { continuation.resume(returning: $0) }
 72            }
 73        }
 74    }
 75
 76    /// Ends the prompt with an answer, or nil to cancel, and gives the editor the keys back.
 77    func answer(_ text: String?) {
 78        guard let request = prompt else { return }
 79        prompt = nil
 80        if let textView = editor?.textView { textView.window?.makeFirstResponder(textView) }
 81        request.reply(text)
 82    }
 83
 84    /// An export or table recalculation running in Emacs, for Cancel Running Task.
 85    private(set) var emacsTask: Task<Void, Never>?
 86    private var emacsSerial = 0
 87
 88    /// Runs `work` as the Emacs task, cancelling the one before.
 89    func runInEmacs(_ work: @escaping @MainActor () async -> Void) {
 90        emacsTask?.cancel()
 91        emacsSerial += 1
 92        let serial = emacsSerial
 93        emacsTask = Task {
 94            await work()
 95            if emacsSerial == serial { emacsTask = nil }
 96        }
 97    }
 98
 99    /// An app command from a menu, run by the main window.
100    private(set) var runRequest: (id: String, serial: Int)?
101    private var runSerial = 0
102
103    func run(_ id: String) {
104        runSerial += 1
105        runRequest = (id, runSerial)
106    }
107
108    /// A capture waiting for the capture window: the template key and the link properties for
109    /// its escapes (org-protocol), or the agenda day to schedule the entry on.
110    var captureRequest: (template: String?, properties: [String: String], day: Int?, serial: Int)?
111    private var captureSerial = 0
112
113    /// Capture from an agenda day, as `org-agenda-capture`: that day is the capture's date, and
114    /// the entry is scheduled on it. The caller opens the capture window.
115    func capture(on day: Int) {
116        captureSerial += 1
117        captureRequest = (nil, [:], day, captureSerial)
118    }
119
120    /// `org-protocol://capture` and `store-link`.
121    func handle(protocolURL url: String) {
122        switch OrgProtocol.parse(url) {
123        case .capture(let template, let properties):
124            captureSerial += 1
125            captureRequest = (template, properties, nil, captureSerial)
126            run("app.capture")
127        case .storeLink(let link, let title):
128            storeLink(StoredLink(link: link, description: title))
129            NSPasteboard.general.clearContents()
130            NSPasteboard.general.setString(link, forType: .string)
131        case nil:
132            show("orgstar handles org-protocol capture and store-link")
133        }
134    }
135
136    func jump(path: String, offset: Int) {
137        jumpID += 1
138        jumpRequest = (path, offset, jumpID)
139    }
140
141    func show(_ text: String) {
142        messageID += 1
143        let id = messageID
144        message = text
145        Task {
146            try? await Task.sleep(for: .seconds(4))
147            if messageID == id { message = nil }
148        }
149    }
150}
151
152struct PromptRequest: Identifiable {
153    let id = UUID()
154    let prompt: Prompt
155    let reply: (String?) -> Void
156}
157
158@MainActor
159final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDelegate {
160    var session: DocumentSession?
161    var commands: AppCommands?
162
163    func applicationDidFinishLaunching(_ notification: Notification) {
164        if SystemReminderCenter.isAvailable { UNUserNotificationCenter.current().delegate = self }
165    }
166
167    /// `:session` interpreters end with the app.
168    func applicationWillTerminate(_ notification: Notification) {
169        BabelSessions.shared.stopAll()
170    }
171
172    /// Reminders show while Orgstar is in front too.
173    nonisolated func userNotificationCenter(
174        _ center: UNUserNotificationCenter, willPresent notification: UNNotification
175    ) async -> UNNotificationPresentationOptions {
176        [.banner, .sound, .list]
177    }
178
179    /// Clicking a reminder shows its entry.
180    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
181        let info = response.notification.request.content.userInfo
182        guard let path = info["path"] as? String, let offset = info["offset"] as? Int else { return }
183        await MainActor.run {
184            NSApp.activate()
185            commands?.jump(path: path, offset: offset)
186        }
187    }
188
189    /// Files opened from Finder, `open`, or a drop on the Dock icon: each opens as a buffer.
190    /// Ones that arrive before the window is ready wait for it (`pendingOpens`).
191    static var pendingOpens: [String] = []
192
193    func application(_ application: NSApplication, open urls: [URL]) {
194        let paths = urls.filter(\.isFileURL).map(\.path)
195        let links = urls.filter { $0.scheme == "org-protocol" }.map(\.absoluteString)
196        guard let commands, let session else {
197            Self.pendingOpens += paths
198            Self.pendingLinks += links
199            return
200        }
201        NSApp.activate()
202        for path in paths { session.open(path) }
203        for link in links { commands.handle(protocolURL: link) }
204    }
205
206    /// org-protocol links that arrive before the window is ready.
207    static var pendingLinks: [String] = []
208
209    func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true }
210
211    func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
212        guard let session else { return .terminateNow }
213        BufferRestore.save(session)
214        return UnsavedChanges.resolve(session, paths: session.openPaths) ? .terminateNow : .terminateCancel
215    }
216}
217
218/// Unsaved edits when leaving a file or quitting.
219@MainActor
220enum UnsavedChanges {
221    /// Whether the open file can be left: saved in automatic mode, or as the user chooses in
222    /// explicit mode. A save that fails or conflicts keeps the file open.
223    static func resolve(_ session: DocumentSession) -> Bool {
224        guard session.isDirty else { return true }
225        if session.saveMode == .automatic { return session.save() }
226        let alert = NSAlert()
227        alert.messageText = "Save changes to \(session.path.map { ($0 as NSString).lastPathComponent } ?? "this file")?"
228        alert.informativeText = "Your changes will be lost if you don't save them."
229        alert.addButton(withTitle: "Save")
230        alert.addButton(withTitle: "Don't Save")
231        alert.addButton(withTitle: "Cancel")
232        switch alert.runModal() {
233        case .alertFirstButtonReturn: return session.save()
234        case .alertSecondButtonReturn: return true
235        default: return false
236        }
237    }
238
239    /// Whether the buffers of `paths` can be closed: saved in automatic mode, or as the user
240    /// chooses for all of them in explicit mode.
241    static func resolve(_ session: DocumentSession, paths: [String]) -> Bool {
242        let dirty = paths.filter(session.dirtyPaths.contains)
243        guard !dirty.isEmpty else { return true }
244        if session.saveMode == .automatic { return dirty.map(session.save).allSatisfy { $0 } }
245        if dirty == [session.path] { return resolve(session) }
246        let alert = NSAlert()
247        alert.messageText = "Save changes to \(dirty.count) files?"
248        alert.informativeText = dirty.map { ($0 as NSString).lastPathComponent }.joined(separator: ", ")
249        alert.addButton(withTitle: "Save All")
250        alert.addButton(withTitle: "Don't Save")
251        alert.addButton(withTitle: "Cancel")
252        switch alert.runModal() {
253        case .alertFirstButtonReturn: return dirty.map(session.save).allSatisfy { $0 }
254        case .alertSecondButtonReturn: return true
255        default: return false
256        }
257    }
258}
259
260/// The open buffers, their order and carets, kept for the next launch.
261@MainActor
262enum BufferRestore {
263    private static let key = "openBuffers"
264
265    struct State: Codable {
266        var paths: [String]
267        var current: String?
268        var carets: [String: Int]
269    }
270
271    static func save(_ session: DocumentSession, defaults: UserDefaults = .standard) {
272        var carets: [String: Int] = [:]
273        for path in session.openPaths { carets[path] = session.caret(of: path) }
274        let state = State(paths: session.openPaths, current: session.path, carets: carets)
275        if let data = try? JSONEncoder().encode(state) { defaults.set(data, forKey: key) }
276    }
277
278    /// Opens the buffers that were open, in order, and returns the carets to show them at.
279    static func restore(_ session: DocumentSession, defaults: UserDefaults = .standard) -> [String: Int] {
280        guard let data = defaults.data(forKey: key), let state = try? JSONDecoder().decode(State.self, from: data) else { return [:] }
281        let existing = state.paths.filter { FileManager.default.fileExists(atPath: $0) }
282        for path in existing { session.open(path) }
283        if let current = state.current, existing.contains(current) { session.open(current) }
284        return state.carets
285    }
286}
287
288@main
289struct OrgstarApp: App {
290    @NSApplicationDelegateAdaptor private var delegate: AppDelegate
291    @State private var workspace = Result {
292        try WorkspaceModel(directory: WorkspaceModel.defaultDirectory, settings: .with(todoKeywords: Preferences.orgSettings))
293    }
294    @State private var commands = AppCommands()
295    @State private var clock = ClockModel()
296    @State private var scheduler = SystemReminderCenter.isAvailable ? ReminderScheduler(center: SystemReminderCenter()) : nil
297    @State private var session: DocumentSession = {
298        let session = DocumentSession()
299        session.defaults = Preferences.orgSettings
300        return session
301    }()
302
303    init() {
304        // Debug builds, and runs with ORGSTAR_PERF set: main-thread stalls in the console.
305        #if DEBUG
306        Perf.watchMainThread()
307        #else
308        if ProcessInfo.processInfo.environment["ORGSTAR_PERF"] != nil { Perf.watchMainThread() }
309        #endif
310    }
311
312    var body: some Scene {
313        Window("orgstar", id: "main") {
314            switch workspace {
315            case .success(let model):
316                ContentView(workspace: model, session: session, commands: commands, scheduler: scheduler, clock: clock)
317                    .environment(\.orgTheme, ConfigSync.shared.theme)
318                    .onAppear {
319                        delegate.session = session
320                        delegate.commands = commands
321                        CaptureIntent.environment = (model, session, clock, commands)
322                    }
323            case .failure(let error):
324                ContentUnavailableView("Can't open the index", systemImage: "exclamationmark.triangle", description: Text(error.localizedDescription))
325            }
326        }
327        .defaultSize(width: 1280, height: 860)
328        WindowGroup("Editor", id: "editor") {
329            if case .success = workspace {
330                EditorWindowView(session: session, commands: commands, clock: clock)
331                    .environment(\.orgTheme, ConfigSync.shared.theme)
332            }
333        }
334        .defaultSize(width: 900, height: 700)
335        Window("Agenda", id: "agenda") {
336            if case .success(let model) = workspace {
337                AgendaView(workspace: model, session: session, commands: commands, scheduler: scheduler, clock: clock)
338                    .environment(\.orgTheme, ConfigSync.shared.theme)
339            }
340        }
341        .defaultSize(width: 760, height: 720)
342        Window("Board", id: "board") {
343            if case .success(let model) = workspace {
344                BoardView(workspace: model, session: session, commands: commands)
345                    .environment(\.orgTheme, ConfigSync.shared.theme)
346            }
347        }
348        .defaultSize(width: 1100, height: 700)
349        Window("Clock Report", id: "clock-report") {
350            if case .success(let model) = workspace {
351                ClockReportView(workspace: model)
352            }
353        }
354        .defaultSize(width: 860, height: 560)
355        Window("Capture", id: "capture") {
356            if case .success(let model) = workspace {
357                CaptureView(workspace: model, session: session, commands: commands, clock: clock)
358            }
359        }
360        .windowResizability(.contentSize)
361        .windowLevel(.floating)
362        .commands {
363            CommandGroup(after: .newItem) {
364                Button("Add Folder…") { commands.showingFolderPicker = true }
365                    .keyboardShortcut("o", modifiers: [.command, .shift])
366                Button("Quick Open…") { commands.showingQuickOpen = true }
367                    .keyboardShortcut("p")
368                Button("Command Palette…") { commands.showingPalette = true }
369                    .keyboardShortcut("p", modifiers: [.command, .shift])
370            }
371            CommandGroup(after: .saveItem) {
372                Menu("Export") {
373                    ForEach(EditorCommands.all.filter { $0.id.hasPrefix("app.export.") }, id: \.id) { command in
374                        Button(command.title) { commands.run(command.id) }
375                    }
376                }
377                .disabled(session.path == nil)
378            }
379            CommandGroup(replacing: .saveItem) {
380                Button("Close Buffer") {
381                    // ⌘W closes the buffer in the main window, and other windows themselves.
382                    if let key = NSApp.keyWindow, key.identifier?.rawValue.contains("main") != true {
383                        key.performClose(nil)
384                    } else {
385                        commands.run("app.buffer.kill")
386                    }
387                }
388                .keyboardShortcut("w")
389                Button("Close Window") { NSApp.keyWindow?.performClose(nil) }
390                    .keyboardShortcut("w", modifiers: [.command, .shift])
391                Divider()
392                Button("Save") {
393                    if !session.save(), session.conflict != nil { commands.showingConflict = true }
394                }
395                .keyboardShortcut("s")
396                .disabled(session.path == nil || session.isReadOnly)
397                Button("Save All") { commands.run("app.save-all") }
398                    .keyboardShortcut("s", modifiers: [.command, .option])
399                    .disabled(session.dirtyPaths.isEmpty)
400            }
401            CommandGroup(after: .sidebar) {
402                Button("Split Pane Below") { commands.run("app.split-below") }
403                    .keyboardShortcut("2", modifiers: [.command, .control])
404                Button("Split Pane Right") { commands.run("app.split-right") }
405                    .keyboardShortcut("3", modifiers: [.command, .control])
406                Button("Close Pane") { commands.run("app.pane-close") }
407                    .keyboardShortcut("0", modifiers: [.command, .control])
408                Button("Close Other Panes") { commands.run("app.pane-only") }
409                    .keyboardShortcut("1", modifiers: [.command, .control])
410                Button("Next Pane") { commands.run("app.pane-next") }
411                    .keyboardShortcut("`", modifiers: [.command, .option])
412                Divider()
413                Button("Show or Hide Outline") { commands.run("app.toggle-outline") }
414                    .keyboardShortcut("o", modifiers: [.command, .option])
415                Button("Show or Hide Backlinks") { commands.run("app.toggle-backlinks") }
416                Button("Show or Hide Columns and Clock") { commands.run("app.toggle-inspector") }
417                    .keyboardShortcut("i", modifiers: [.command, .option])
418                MarkupToggle()
419                Button("Truncate or Wrap Long Lines") { commands.run("editor.toggle-truncate-lines") }
420            }
421            CommandGroup(after: .pasteboard) {
422                Divider()
423                FindMenu(commands: commands)
424            }
425            CommandGroup(after: .textEditing) {
426                Button("Cancel Running Task") { commands.run("app.babel.cancel") }
427                    .keyboardShortcut(".")
428                    .disabled(!session.isRunningBabel && commands.emacsTask == nil)
429                Button("Search Notes") { commands.focusSearch = true }
430                    .keyboardShortcut("f", modifiers: [.command, .shift])
431            }
432            CommandGroup(before: .windowList) {
433                AgendaMenuItem()
434                Divider()
435                Button("Switch to Buffer…") { commands.run("app.buffer.switch") }
436                Button("Next Buffer") { commands.run("app.buffer.next") }
437                    .keyboardShortcut("]", modifiers: [.command, .shift])
438                Button("Previous Buffer") { commands.run("app.buffer.previous") }
439                    .keyboardShortcut("[", modifiers: [.command, .shift])
440                Divider()
441            }
442            CommandGroup(after: .newItem) {
443                Button("Capture…") { commands.run("app.capture") }
444                    .keyboardShortcut("n", modifiers: [.command, .shift])
445                Button("New Window") { commands.run("app.window-new") }
446                    .keyboardShortcut("n", modifiers: [.command, .option])
447            }
448        }
449        .commands {
450            CommandMenu("Org") {
451                ClockMenu(commands: commands, clock: clock)
452                Divider()
453                OrgMenuItems(commands: commands)
454            }
455        }
456        .commands {
457            CommandGroup(after: .appSettings) {
458                Button("Edit Config File") { commands.jump(path: UserConfig.configFile.path, offset: 0) }
459                    .keyboardShortcut(",", modifiers: [.command, .option])
460            }
461        }
462        Settings {
463            SettingsView(commands: commands, workspace: try? workspace.get())
464        }
465    }
466}
467
468/// The Org menu: every org command, with the keys that run it in the current keymap.
469struct OrgMenuItems: View {
470    let commands: AppCommands
471
472    var body: some View {
473        ForEach(EditorCommands.all.filter { $0.id.hasPrefix("org.") }, id: \.id) { command in
474            Button {
475                commands.editor?.run(command.id)
476            } label: {
477                Text(command.title)
478                if let keys = commands.keyLabel(for: command.id) { Text(keys) }
479            }
480            .disabled(commands.editor == nil)
481        }
482    }
483}
484
485/// View ▸ Show Markup (link brackets and targets, emphasis markers) and Show Line Numbers.
486struct MarkupToggle: View {
487    @AppStorage("showTabBar") private var showTabBar = false
488    @AppStorage("showMarkup") private var showMarkup = false
489    @AppStorage("showLineNumbers") private var showLineNumbers = true
490
491    var body: some View {
492        Toggle("Show Markup", isOn: $showMarkup)
493            .keyboardShortcut("m", modifiers: [.command, .shift])
494        Toggle("Show Line Numbers", isOn: $showLineNumbers)
495            .keyboardShortcut("l", modifiers: [.command, .shift])
496        Toggle("Show Tab Bar", isOn: $showTabBar)
497    }
498}
499
500/// Edit ▸ Find: the editor's find bar.
501struct FindMenu: View {
502    let commands: AppCommands
503
504    var body: some View {
505        Menu("Find") {
506            item("Find…", "edit.find", "f")
507            item("Find and Replace…", "edit.replace", "f", [.command, .option])
508            item("Find Next", "edit.find-next", "g")
509            item("Find Previous", "edit.find-previous", "g", [.command, .shift])
510            item("Use Selection for Find", "edit.use-selection-for-find", "e")
511        }
512    }
513
514    private func item(_ title: String, _ id: String, _ key: KeyEquivalent, _ modifiers: EventModifiers = .command) -> some View {
515        Button(title) { commands.editor?.run(id) }
516            .keyboardShortcut(key, modifiers: modifiers)
517            .disabled(commands.editor == nil)
518    }
519}
520
521/// Window ▸ Agenda.
522struct AgendaMenuItem: View {
523    @Environment(\.openWindow) private var openWindow
524
525    var body: some View {
526        Button("Agenda") { openWindow(id: "agenda") }
527            .keyboardShortcut("a", modifiers: [.command, .shift])
528        Button("Board") { openWindow(id: "board") }
529            .keyboardShortcut("b", modifiers: [.command, .shift])
530    }
531}
532
533struct SettingsView: View {
534    let commands: AppCommands
535    let workspace: WorkspaceModel?
536    @State private var importing = false
537    @Environment(\.openWindow) private var openWindow
538    @AppStorage("saveMode") private var saveMode = SaveMode.automatic
539    @AppStorage("keymap") private var preset = KeymapPreset.emacs
540    @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
541    @AppStorage("tagsColumn") private var tagsColumn = -77
542    @AppStorage("headingAfterSubtree") private var headingAfterSubtree = true
543    @AppStorage("splitLine") private var splitLine = false
544    @AppStorage("alphabeticalLists") private var alphabeticalLists = true
545    @AppStorage("fillColumn") private var fillColumn = 80
546    @AppStorage("hiddenMarkers") private var hiddenMarkers = true
547    @AppStorage("prettyEntities") private var prettyEntities = true
548    @AppStorage("startupTruncated") private var startupTruncated = false
549    @AppStorage("todoKeywords") private var todoKeywords = Preferences.defaultTodoKeywords
550    @AppStorage("enforceTodoDependencies") private var enforceTodoDependencies = false
551    @AppStorage("enforceTodoCheckboxDependencies") private var enforceTodoCheckboxDependencies = false
552    @AppStorage("agendaSpan") private var agendaSpan = 10
553    @AppStorage("agendaStartOffset") private var agendaStartOffset = 0
554    @AppStorage("agendaSubfolders") private var agendaSubfolders = false
555    @AppStorage("agendaShowAllDates") private var agendaShowAllDates = false
556    @AppStorage("agendaDimBlockedTasks") private var agendaDimBlockedTasks = "t"
557    @AppStorage("calendarEvents") private var calendarEvents = false
558    @AppStorage("calendarEventCalendars") private var calendarEventCalendars = ""
559    @State private var calendars: [(id: String, title: String, color: RGBA?)] = []
560    @AppStorage("reminders") private var reminders = true
561    @AppStorage("reminderLead") private var reminderLead = 12
562    @AppStorage("clockIdleTime") private var clockIdleTime = 0
563    @AppStorage("clockHistoryLength") private var clockHistoryLength = 5
564    @AppStorage("globalCapture") private var globalCapture = true
565    @AppStorage("settingsTab") private var tab = "general"
566    @AppStorage("showHiddenFiles") private var showHiddenFiles = true
567    @AppStorage("themeFont") private var themeFont = ""
568    @AppStorage("themeFontSize") private var themeFontSize = 13
569    @AppStorage("themeLineSpacing") private var themeLineSpacing = 2
570    @AppStorage("themeHeadingStep") private var themeHeadingStep = 1
571
572    /// Installed monospaced font families.
573    private static let monospacedFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in
574        NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == true
575    }
576
577    var body: some View {
578        TabView(selection: $tab) {
579            Tab("General", systemImage: "gearshape", value: "general") { general }
580            Tab("Editing", systemImage: "text.alignleft", value: "editing") { editing }
581            Tab("Appearance", systemImage: "paintpalette", value: "appearance") { appearance }
582            Tab("Agenda", systemImage: "calendar", value: "agenda") { agenda }
583            Tab("Capture", systemImage: "tray.and.arrow.down", value: "capture") { capture }
584        }
585        .frame(width: 600)
586    }
587
588    private func editConfig() {
589        ConfigSync.shared.start()
590        openWindow(id: "main")
591        commands.jump(path: UserConfig.configFile.path, offset: 0)
592    }
593
594    private var general: some View {
595        Form {
596            Section {
597                LabeledContent("config.toml") {
598                    HStack {
599                        Button("Edit in orgstar") { editConfig() }
600                        Button("Open with Default App") { NSWorkspace.shared.open(UserConfig.configFile) }
601                        Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([UserConfig.configFile]) }
602                    }
603                }
604                LabeledContent("Emacs") {
605                    Button("Import from Emacs…") { importing = true }
606                }
607            } footer: {
608                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.")
609                    .settingsFooter()
610            }
611            Section {
612                Picker("Save files", selection: $saveMode) {
613                    Text("Automatically, when typing stops").tag(SaveMode.automatic)
614                    Text("Only with File ▸ Save (⌘S)").tag(SaveMode.explicit)
615                }
616                .pickerStyle(.radioGroup)
617            }
618            Section {
619                Picker("Keys", selection: $preset) {
620                    ForEach(KeymapPreset.allCases, id: \.self) { Text($0.title).tag($0) }
621                }
622                Toggle("Show hidden files and folders", isOn: $showHiddenFiles)
623                Picker("Option as Meta", selection: $optionAsMeta) {
624                    Text("Left Option").tag(OptionAsMeta.left.rawValue)
625                    Text("Right Option").tag(OptionAsMeta.right.rawValue)
626                    Text("Both").tag(OptionAsMeta([.left, .right]).rawValue)
627                    Text("Neither").tag(0)
628                }
629            } footer: {
630                Text("Your own bindings go in \(KeymapLoader.userFile.path), on top of the preset.")
631                    .settingsFooter()
632            }
633        }
634        .formStyle(.grouped)
635        .frame(height: 330)
636        .sheet(isPresented: $importing) { EmacsImportView(workspace: workspace) }
637    }
638
639    private var editing: some View {
640        Form {
641            Section {
642                Picker("Tags", selection: $tagsColumn) {
643                    Text("Aligned to end at column 77").tag(-77)
644                    Text("One space after the title").tag(0)
645                }
646                Toggle("M-RET adds the new heading after the subtree", isOn: $headingAfterSubtree)
647                Toggle("M-RET splits the line at the caret", isOn: $splitLine)
648                Toggle("Lists can use letters (a. b. c.)", isOn: $alphabeticalLists)
649                Stepper("M-q fills to column \(fillColumn)", value: $fillColumn, in: 40...200)
650            }
651            Section {
652                Toggle("Long lines run off the edge instead of wrapping (org-startup-truncated)", isOn: $startupTruncated)
653            } footer: {
654                Text("Applies to files as they open. View ▸ Truncate or Wrap Long Lines switches the current file.")
655                    .settingsFooter()
656            }
657            Section {
658                Toggle("Emacs hides emphasis markers (org-hide-emphasis-markers)", isOn: $hiddenMarkers)
659                Toggle("Emacs shows entities as characters (org-pretty-entities)", isOn: $prettyEntities)
660            } footer: {
661                Text("Tags, tables and M-q measure text as your Emacs displays it, so both write the same file.")
662                    .settingsFooter()
663            }
664            Section {
665                TextField("Default TODO keywords", text: $todoKeywords, axis: .vertical)
666            } footer: {
667                Text("For files without #+TODO, in #+TODO syntax, one sequence per line. Takes effect when orgstar restarts.")
668                    .settingsFooter()
669            }
670            Section {
671                Toggle("Entries can't be done before their TODO children (org-enforce-todo-dependencies)", isOn: $enforceTodoDependencies)
672                Toggle("Entries can't be done with unchecked boxes (org-enforce-todo-checkbox-dependencies)", isOn: $enforceTodoCheckboxDependencies)
673            } footer: {
674                Text("Under a parent with the ORDERED property (Toggle ORDERED Property, C-c C-x o), TODO children are also done in order.")
675                    .settingsFooter()
676            }
677        }
678        .formStyle(.grouped)
679        .frame(height: 640)
680    }
681
682    private var appearance: some View {
683        Form {
684            Section {
685                Picker("Font", selection: $themeFont) {
686                    Text("System monospaced").tag("")
687                    Divider()
688                    ForEach(Self.monospacedFamilies, id: \.self) { Text($0).tag($0) }
689                    if !themeFont.isEmpty, !Self.monospacedFamilies.contains(themeFont) { Text(themeFont).tag(themeFont) }
690                }
691                Stepper("Size: \(themeFontSize) pt", value: $themeFontSize, in: 8...36)
692                Stepper("Line spacing: \(themeLineSpacing) pt", value: $themeLineSpacing, in: 0...16)
693                Stepper("Headings grow by \(themeHeadingStep) pt a level", value: $themeHeadingStep, in: 0...8)
694            } footer: {
695                Text("Tags and tables line up in columns, so a monospaced font keeps them straight.")
696                    .settingsFooter()
697            }
698            Section {
699                LabeledContent("Colors") {
700                    HStack {
701                        Button("Edit in config.toml") { editConfig() }
702                        Button("Show Default Theme") {
703                            openWindow(id: "main")
704                            commands.jump(path: UserConfig.directory.appendingPathComponent("default-theme.toml").path, offset: 0)
705                        }
706                    }
707                }
708            } footer: {
709                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.")
710                    .settingsFooter()
711            }
712        }
713        .formStyle(.grouped)
714        .frame(height: 380)
715    }
716
717    private var agenda: some View {
718        Form {
719            Section {
720                Stepper("Agenda shows \(agendaSpan) days", value: $agendaSpan, in: 1...366)
721                Stepper(agendaStartOffset == 0 ? "Agenda starts today" : "Agenda starts \(-agendaStartOffset) days before today", value: $agendaStartOffset, in: -14...0)
722                Toggle("Include files in subfolders", isOn: $agendaSubfolders)
723                Toggle("Show days without entries", isOn: $agendaShowAllDates)
724                Picker("Blocked entries", selection: $agendaDimBlockedTasks) {
725                    Text("Dimmed").tag("t")
726                    Text("Hidden").tag("invisible")
727                    Text("Shown as usual").tag("nil")
728                }
729            }
730            Section {
731                Toggle("Show events from Calendar", isOn: $calendarEvents)
732                if calendarEvents {
733                    if calendars.isEmpty {
734                        Text(CalendarEvents.isAuthorized ? "No calendars." : "Allow orgstar to read your calendars in System Settings ▸ Privacy & Security ▸ Calendars.")
735                            .foregroundStyle(.secondary)
736                    }
737                    ForEach(calendars, id: \.id) { calendar in
738                        Toggle(isOn: calendarChosen(calendar)) {
739                            HStack(spacing: 6) {
740                                Circle()
741                                    .fill(calendar.color.map { Color(.sRGB, red: $0.red, green: $0.green, blue: $0.blue, opacity: $0.alpha) } ?? .secondary)
742                                    .frame(width: 8, height: 8)
743                                Text(calendar.title)
744                            }
745                        }
746                    }
747                }
748            } footer: {
749                Text("Events show in the agenda read-only; double-click one to open it in Calendar. New calendars show while every calendar is checked.")
750                    .settingsFooter()
751            }
752            .task(id: calendarEvents) {
753                let allowed = calendarEvents ? await CalendarAccess.events.requestAccess() : false
754                calendars = allowed ? CalendarAccess.events.calendars() : []
755            }
756            Section {
757                Toggle("Notify before timed agenda entries", isOn: $reminders)
758                Stepper("\(reminderLead) minutes before", value: $reminderLead, in: 0...120)
759                    .disabled(!reminders)
760            } footer: {
761                Text("An entry's APPT_WARNTIME property overrides the lead time.")
762                    .settingsFooter()
763            }
764            Section {
765                Toggle("Ask what to do with idle time while clocked in", isOn: Binding {
766                    clockIdleTime > 0
767                } set: { on in
768                    clockIdleTime = on ? 15 : 0
769                })
770                Stepper("After \(max(clockIdleTime, 1)) minutes without keyboard or mouse input", value: $clockIdleTime, in: 1...240)
771                    .disabled(clockIdleTime == 0)
772                Stepper("Remember \(clockHistoryLength) recently clocked entries", value: $clockHistoryLength, in: 1...35)
773            } footer: {
774                Text("org-clock-idle-time and org-clock-history-length. Org ▸ Clock lists the recent entries.")
775                    .settingsFooter()
776            }
777        }
778        .formStyle(.grouped)
779        .frame(height: 560)
780    }
781
782    /// `calendar-event-calendars`: empty for every calendar, else the titles checked.
783    private func calendarChosen(_ calendar: (id: String, title: String, color: RGBA?)) -> Binding<Bool> {
784        let chosen = calendarEventCalendars.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
785        return Binding {
786            CalendarEvents.chooses(id: calendar.id, title: calendar.title, chosen: chosen)
787        } set: { on in
788            var titles = calendars.map(\.title).filter { title in
789                chosen.isEmpty || chosen.contains(title) || chosen.contains(calendars.first { $0.title == title }?.id ?? "")
790            }
791            titles.removeAll { $0 == calendar.title }
792            if on { titles.append(calendar.title) }
793            // An empty list means every calendar; turning events off hides them all.
794            guard !titles.isEmpty else { return }
795            calendarEventCalendars = Set(titles) == Set(calendars.map(\.title)) ? "" : titles.joined(separator: ", ")
796        }
797    }
798
799    private var capture: some View {
800        Form {
801            Section {
802                Toggle("⌃⌥Space opens Capture from any app", isOn: $globalCapture)
803            } footer: {
804                Text("Templates go in \(CaptureTemplates.userFile.path).")
805                    .settingsFooter()
806            }
807        }
808        .formStyle(.grouped)
809        .frame(height: 160)
810    }
811}
812
813private extension Text {
814    func settingsFooter() -> some View {
815        font(.caption)
816            .foregroundStyle(.secondary)
817            .textSelection(.enabled)
818            .frame(maxWidth: .infinity, alignment: .leading)
819    }
820}
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