Sources/Orgstar/OrgstarApp.swift

8c221170c5ed1f01bcb7cabccac77177aa399d9a
orgstar/Sources/Orgstar/OrgstarApp.swift history · blame · raw

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