Sources/Orgstar/OrgstarApp.swift

065a5cf4c58176da6374247e13bd1b1580a10a86
orgstar/Sources/Orgstar/OrgstarApp.swift

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