Sources/Orgstar/OrgstarApp.swift

73230beed303498a3ed5f7f1886cd9f3d9beacd1
orgstar/Sources/Orgstar/OrgstarApp.swift

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