Sources/Orgstar/OrgstarApp.swift

3f183dc5a69542840ae20a73ec755d1148b354dd
orgstar/Sources/Orgstar/OrgstarApp.swift history · blame · raw

668 lines · 29181 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                Button("Show or Hide Backlinks") { commands.run("app.toggle-backlinks") }
353                Button("Show or Hide Columns and Clock") { commands.run("app.toggle-inspector") }
354                    .keyboardShortcut("i", modifiers: [.command, .option])
355                    .keyboardShortcut("o", modifiers: [.command, .option])
356                MarkupToggle()
357            }
358            CommandGroup(after: .pasteboard) {
359                Divider()
360                FindMenu(commands: commands)
361            }
362            CommandGroup(after: .textEditing) {
363                Button("Cancel Running Block") { commands.run("app.babel.cancel") }
364                    .keyboardShortcut(".")
365                    .disabled(!session.isRunningBabel)
366                Button("Search Notes") { commands.focusSearch = true }
367                    .keyboardShortcut("f", modifiers: [.command, .shift])
368            }
369            CommandGroup(before: .windowList) {
370                AgendaMenuItem()
371                Divider()
372                Button("Switch to Buffer…") { commands.run("app.buffer.switch") }
373                Button("Next Buffer") { commands.run("app.buffer.next") }
374                    .keyboardShortcut("]", modifiers: [.command, .shift])
375                Button("Previous Buffer") { commands.run("app.buffer.previous") }
376                    .keyboardShortcut("[", modifiers: [.command, .shift])
377                Divider()
378            }
379            CommandGroup(after: .newItem) {
380                Button("Capture…") { commands.run("app.capture") }
381                    .keyboardShortcut("n", modifiers: [.command, .shift])
382            }
383        }
384        .commands {
385            CommandMenu("Org") {
386                OrgMenuItems(commands: commands)
387            }
388        }
389        .commands {
390            CommandGroup(after: .appSettings) {
391                Button("Edit Config File") { commands.jump(path: UserConfig.configFile.path, offset: 0) }
392                    .keyboardShortcut(",", modifiers: [.command, .option])
393            }
394        }
395        Settings {
396            SettingsView(commands: commands, workspace: try? workspace.get())
397        }
398    }
399}
400
401/// The Org menu: every org command, with the keys that run it in the current keymap.
402struct OrgMenuItems: View {
403    let commands: AppCommands
404
405    var body: some View {
406        ForEach(EditorCommands.all.filter { $0.id.hasPrefix("org.") }, id: \.id) { command in
407            Button {
408                commands.editor?.run(command.id)
409            } label: {
410                Text(command.title)
411                if let keys = commands.keyLabel(for: command.id) { Text(keys) }
412            }
413            .disabled(commands.editor == nil)
414        }
415    }
416}
417
418/// View ▸ Show Markup (link brackets and targets, emphasis markers) and Show Line Numbers.
419struct MarkupToggle: View {
420    @AppStorage("showTabBar") private var showTabBar = false
421    @AppStorage("showMarkup") private var showMarkup = false
422    @AppStorage("showLineNumbers") private var showLineNumbers = true
423
424    var body: some View {
425        Toggle("Show Markup", isOn: $showMarkup)
426            .keyboardShortcut("m", modifiers: [.command, .shift])
427        Toggle("Show Line Numbers", isOn: $showLineNumbers)
428            .keyboardShortcut("l", modifiers: [.command, .shift])
429        Toggle("Show Tab Bar", isOn: $showTabBar)
430    }
431}
432
433/// Edit ▸ Find: the editor's find bar.
434struct FindMenu: View {
435    let commands: AppCommands
436
437    var body: some View {
438        Menu("Find") {
439            item("Find…", "edit.find", "f")
440            item("Find and Replace…", "edit.replace", "f", [.command, .option])
441            item("Find Next", "edit.find-next", "g")
442            item("Find Previous", "edit.find-previous", "g", [.command, .shift])
443            item("Use Selection for Find", "edit.use-selection-for-find", "e")
444        }
445    }
446
447    private func item(_ title: String, _ id: String, _ key: KeyEquivalent, _ modifiers: EventModifiers = .command) -> some View {
448        Button(title) { commands.editor?.run(id) }
449            .keyboardShortcut(key, modifiers: modifiers)
450            .disabled(commands.editor == nil)
451    }
452}
453
454/// Window ▸ Agenda.
455struct AgendaMenuItem: View {
456    @Environment(\.openWindow) private var openWindow
457
458    var body: some View {
459        Button("Agenda") { openWindow(id: "agenda") }
460            .keyboardShortcut("a", modifiers: [.command, .shift])
461        Button("Board") { openWindow(id: "board") }
462            .keyboardShortcut("b", modifiers: [.command, .shift])
463    }
464}
465
466struct SettingsView: View {
467    let commands: AppCommands
468    let workspace: WorkspaceModel?
469    @State private var importing = false
470    @Environment(\.openWindow) private var openWindow
471    @AppStorage("saveMode") private var saveMode = SaveMode.automatic
472    @AppStorage("keymap") private var preset = KeymapPreset.emacs
473    @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
474    @AppStorage("tagsColumn") private var tagsColumn = -77
475    @AppStorage("headingAfterSubtree") private var headingAfterSubtree = true
476    @AppStorage("splitLine") private var splitLine = false
477    @AppStorage("alphabeticalLists") private var alphabeticalLists = true
478    @AppStorage("fillColumn") private var fillColumn = 80
479    @AppStorage("hiddenMarkers") private var hiddenMarkers = true
480    @AppStorage("prettyEntities") private var prettyEntities = true
481    @AppStorage("todoKeywords") private var todoKeywords = Preferences.defaultTodoKeywords
482    @AppStorage("agendaSpan") private var agendaSpan = 10
483    @AppStorage("agendaStartOffset") private var agendaStartOffset = -3
484    @AppStorage("agendaSubfolders") private var agendaSubfolders = false
485    @AppStorage("reminders") private var reminders = true
486    @AppStorage("reminderLead") private var reminderLead = 12
487    @AppStorage("globalCapture") private var globalCapture = true
488    @AppStorage("settingsTab") private var tab = "general"
489    @AppStorage("showHiddenFiles") private var showHiddenFiles = true
490    @AppStorage("themeFont") private var themeFont = ""
491    @AppStorage("themeFontSize") private var themeFontSize = 13
492    @AppStorage("themeLineSpacing") private var themeLineSpacing = 2
493    @AppStorage("themeHeadingStep") private var themeHeadingStep = 1
494
495    /// Installed monospaced font families.
496    private static let monospacedFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in
497        NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == true
498    }
499
500    var body: some View {
501        TabView(selection: $tab) {
502            Tab("General", systemImage: "gearshape", value: "general") { general }
503            Tab("Editing", systemImage: "text.alignleft", value: "editing") { editing }
504            Tab("Appearance", systemImage: "paintpalette", value: "appearance") { appearance }
505            Tab("Agenda", systemImage: "calendar", value: "agenda") { agenda }
506            Tab("Capture", systemImage: "tray.and.arrow.down", value: "capture") { capture }
507        }
508        .frame(width: 600)
509    }
510
511    private func editConfig() {
512        ConfigSync.shared.start()
513        openWindow(id: "main")
514        commands.jump(path: UserConfig.configFile.path, offset: 0)
515    }
516
517    private var general: some View {
518        Form {
519            Section {
520                LabeledContent("config.toml") {
521                    HStack {
522                        Button("Edit in Orgstar") { editConfig() }
523                        Button("Open with Default App") { NSWorkspace.shared.open(UserConfig.configFile) }
524                        Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([UserConfig.configFile]) }
525                    }
526                }
527                LabeledContent("Emacs") {
528                    Button("Import from Emacs…") { importing = true }
529                }
530            } footer: {
531                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.")
532                    .settingsFooter()
533            }
534            Section {
535                Picker("Save files", selection: $saveMode) {
536                    Text("Automatically, when typing stops").tag(SaveMode.automatic)
537                    Text("Only with File ▸ Save (⌘S)").tag(SaveMode.explicit)
538                }
539                .pickerStyle(.radioGroup)
540            }
541            Section {
542                Picker("Keys", selection: $preset) {
543                    ForEach(KeymapPreset.allCases, id: \.self) { Text($0.title).tag($0) }
544                }
545                Toggle("Show hidden files and folders", isOn: $showHiddenFiles)
546                Picker("Option as Meta", selection: $optionAsMeta) {
547                    Text("Left Option").tag(OptionAsMeta.left.rawValue)
548                    Text("Right Option").tag(OptionAsMeta.right.rawValue)
549                    Text("Both").tag(OptionAsMeta([.left, .right]).rawValue)
550                    Text("Neither").tag(0)
551                }
552            } footer: {
553                Text("Your own bindings go in \(KeymapLoader.userFile.path), on top of the preset.")
554                    .settingsFooter()
555            }
556        }
557        .formStyle(.grouped)
558        .frame(height: 330)
559        .sheet(isPresented: $importing) { EmacsImportView(workspace: workspace) }
560    }
561
562    private var editing: some View {
563        Form {
564            Section {
565                Picker("Tags", selection: $tagsColumn) {
566                    Text("Aligned to end at column 77").tag(-77)
567                    Text("One space after the title").tag(0)
568                }
569                Toggle("M-RET adds the new heading after the subtree", isOn: $headingAfterSubtree)
570                Toggle("M-RET splits the line at the caret", isOn: $splitLine)
571                Toggle("Lists can use letters (a. b. c.)", isOn: $alphabeticalLists)
572                Stepper("M-q fills to column \(fillColumn)", value: $fillColumn, in: 40...200)
573            }
574            Section {
575                Toggle("Emacs hides emphasis markers (org-hide-emphasis-markers)", isOn: $hiddenMarkers)
576                Toggle("Emacs shows entities as characters (org-pretty-entities)", isOn: $prettyEntities)
577            } footer: {
578                Text("Tags, tables and M-q measure text as your Emacs displays it, so both write the same file.")
579                    .settingsFooter()
580            }
581            Section {
582                TextField("Default TODO keywords", text: $todoKeywords, axis: .vertical)
583            } footer: {
584                Text("For files without #+TODO, in #+TODO syntax, one sequence per line. Takes effect when Orgstar restarts.")
585                    .settingsFooter()
586            }
587        }
588        .formStyle(.grouped)
589        .frame(height: 450)
590    }
591
592    private var appearance: some View {
593        Form {
594            Section {
595                Picker("Font", selection: $themeFont) {
596                    Text("System monospaced").tag("")
597                    Divider()
598                    ForEach(Self.monospacedFamilies, id: \.self) { Text($0).tag($0) }
599                    if !themeFont.isEmpty, !Self.monospacedFamilies.contains(themeFont) { Text(themeFont).tag(themeFont) }
600                }
601                Stepper("Size: \(themeFontSize) pt", value: $themeFontSize, in: 8...36)
602                Stepper("Line spacing: \(themeLineSpacing) pt", value: $themeLineSpacing, in: 0...16)
603                Stepper("Headings grow by \(themeHeadingStep) pt a level", value: $themeHeadingStep, in: 0...8)
604            } footer: {
605                Text("Tags and tables line up in columns, so a monospaced font keeps them straight.")
606                    .settingsFooter()
607            }
608            Section {
609                LabeledContent("Colors") {
610                    HStack {
611                        Button("Edit in config.toml") { editConfig() }
612                        Button("Show Default Theme") {
613                            openWindow(id: "main")
614                            commands.jump(path: UserConfig.directory.appendingPathComponent("default-theme.toml").path, offset: 0)
615                        }
616                    }
617                }
618            } footer: {
619                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.")
620                    .settingsFooter()
621            }
622        }
623        .formStyle(.grouped)
624        .frame(height: 380)
625    }
626
627    private var agenda: some View {
628        Form {
629            Section {
630                Stepper("Agenda shows \(agendaSpan) days", value: $agendaSpan, in: 1...31)
631                Stepper(agendaStartOffset == 0 ? "Agenda starts today" : "Agenda starts \(-agendaStartOffset) days before today", value: $agendaStartOffset, in: -14...0)
632                Toggle("Include files in subfolders", isOn: $agendaSubfolders)
633            }
634            Section {
635                Toggle("Notify before timed agenda entries", isOn: $reminders)
636                Stepper("\(reminderLead) minutes before", value: $reminderLead, in: 0...120)
637                    .disabled(!reminders)
638            } footer: {
639                Text("An entry's APPT_WARNTIME property overrides the lead time.")
640                    .settingsFooter()
641            }
642        }
643        .formStyle(.grouped)
644        .frame(height: 290)
645    }
646
647    private var capture: some View {
648        Form {
649            Section {
650                Toggle("⌃⌥Space opens Capture from any app", isOn: $globalCapture)
651            } footer: {
652                Text("Templates go in \(CaptureTemplates.userFile.path).")
653                    .settingsFooter()
654            }
655        }
656        .formStyle(.grouped)
657        .frame(height: 160)
658    }
659}
660
661private extension Text {
662    func settingsFooter() -> some View {
663        font(.caption)
664            .foregroundStyle(.secondary)
665            .textSelection(.enabled)
666            .frame(maxWidth: .infinity, alignment: .leading)
667    }
668}