Sources/Orgstar/OrgstarApp.swift

0e58e1b1ae285390762ec1b8bf93c882ecc94a02
orgstar/Sources/Orgstar/OrgstarApp.swift history · blame · raw

670 lines · 29301 bytes

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