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