Sources/Orgstar/OrgstarApp.swift

1900873c42a90656ffad9bdb70fb430087de6d1d
orgstar/Sources/Orgstar/OrgstarApp.swift

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