Sources/Orgstar/OrgstarApp.swift

bb0f452e7f55fe1f43d396aeff6b94efa72d3a2f
orgstar/Sources/Orgstar/OrgstarApp.swift

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