Sources/Orgstar/OrgstarApp.swift

f02651ad8efeefa535e05100042f64a39a5b405c
orgstar/Sources/Orgstar/OrgstarApp.swift

726 lines · 31943 bytes

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