Sources/Orgstar/OrgstarApp.swift

71333253c9544b857c22f69f56d3af166b7ef573
orgstar/Sources/Orgstar/OrgstarApp.swift history · blame · raw

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