Sources/Orgstar/OrgstarApp.swift

30f6716c5b85f009c8cee977f3e5e4e4b5df3d09
orgstar/Sources/Orgstar/OrgstarApp.swift history · blame · raw

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