Sources/Orgstar/OrgstarApp.swift
1315 lines · 63733 bytes
1import AppKit
2import OrgApp
3import OrgCore
4import OrgEditorAppKit
5import OrgIndex
6import OrgMathJax
7import OrgPresentation
8#if !APPSTORE
9import OrgPrograms
10#endif
11import SwiftUI
12import UserNotifications
13
14/// Window-level requests the menu bar makes.
15@MainActor
16@Observable
17final class AppCommands {
18 var showingQuickOpen = false
19 var showingFolderPicker = false
20 /// The first-launch sheet, while no folder has been added.
21 var showingWelcome = false
22 /// The notes the main window shows as a sheet.
23 var whatsNew: ReleaseNotes?
24 var focusSearch = false
25 var showingConflict = false
26 var showingPalette = false
27 var showingMessages = false
28 /// The main window's outline pane is shown, for View ▸ Show Outline.
29 var outlineShown = false
30 /// A location another window asked the main window to show.
31 private(set) var jumpRequest: (path: String, offset: Int, id: Int)?
32 private var jumpID = 0
33 /// Days the agenda window should show, from a followed timestamp.
34 var agendaRequest: (start: Int, days: Int)?
35 /// The editor with focus, for menus and the palette.
36 var editor: OrgEditor?
37 /// The editors and text views of every pane in every window.
38 let store = EditorStore()
39 /// The main window is on screen. App commands run there, so an editor window reopens it
40 /// before asking for one.
41 var mainWindowOpen = false
42 /// What every editor is set up with, from the settings; the main window keeps it current.
43 var editorSettings = EditorSettings()
44 /// Runs work outside the text (a table recalculation in Emacs); the main window sets it.
45 var externalHandler: ((ExternalRequest) -> Void)?
46 /// Files and images pasted or dropped on an editor; the main window sets them.
47 var filesHandler: (([URL]) -> Void)?
48 var imageHandler: ((Data, String) -> Void)?
49 #if APPSTORE
50 /// Asks for the folders outside the sidebar's folders that paths need; the main window sets it.
51 var reach: ([String]) -> Bool = { _ in true }
52 #endif
53 /// Tags used across the workspace, for tag completion; the main window sets it.
54 var knownTags: () -> [String] = { [] }
55 /// The index completion asks for headings, values and words; the main window sets it.
56 var completionIndex: IndexStore?
57 /// The pending key prefix, and what can follow it.
58 var pendingKeys: String?
59 /// The editor's evil state in the Doom preset.
60 var editorState: String?
61 /// The keymap in use, for showing keys in menus and the palette.
62 var keymap = KeymapPreset.emacs.keymap
63 var modal = false
64 /// `org-stored-links`, most recent first; kept for the session, as in Emacs.
65 var storedLinks: [StoredLink] = []
66
67 /// Puts `link` first in `storedLinks` and says what happened.
68 func storeLink(_ link: StoredLink) {
69 show(StoredLink.add(link, to: &storedLinks))
70 }
71
72 /// The keys that run `command`, as menus and the palette show them.
73 func keyLabel(for command: String) -> String? {
74 let labels = keymap.keyLabels(for: command, modes: modal ? ["normal", "insert"] : [nil])
75 return labels.isEmpty ? nil : labels.joined(separator: ", ")
76 }
77
78 /// The editor's selection, for the modeline.
79 var selection = NSRange(location: 0, length: 0)
80 /// The focused file and caret, advertised for Handoff.
81 @ObservationIgnored let handoff = HandoffAdvertiser()
82 /// Opens a file continued from another device; the main window sets it.
83 @ObservationIgnored var continueHandoff: ((HandoffPlace) -> Void)?
84 var keyHints: [KeyHint] = []
85 /// A question a command asked, answered in the echo area.
86 private(set) var prompt: PromptRequest?
87 /// The last message from a command or the keymap, kept until the next key or click, as
88 /// Emacs keeps it.
89 private(set) var message: String?
90 /// Recent messages, oldest first, for Messages.
91 private(set) var messages: [String] = []
92 @ObservationIgnored private var inputMonitor: Any?
93
94 func ask(_ prompt: Prompt, reply: @escaping (String?) -> Void) {
95 self.prompt = PromptRequest(prompt: prompt, reply: reply)
96 }
97
98 /// Clock questions in the echo area.
99 var askClock: ClockModel.Ask {
100 { [self] prompt in
101 await withCheckedContinuation { continuation in
102 ask(prompt) { continuation.resume(returning: $0) }
103 }
104 }
105 }
106
107 /// Ends the prompt with an answer, or nil to cancel, and gives the editor the keys back.
108 func answer(_ text: String?) {
109 guard let request = prompt else { return }
110 prompt = nil
111 if let textView = editor?.textView { textView.window?.makeFirstResponder(textView) }
112 request.reply(text)
113 }
114
115 /// An export or table recalculation running in Emacs, for Cancel Running Task.
116 private(set) var emacsTask: Task<Void, Never>?
117 private var emacsSerial = 0
118
119 /// Runs `work` as the Emacs task, cancelling the one before.
120 func runInEmacs(_ work: @escaping @MainActor () async -> Void) {
121 emacsTask?.cancel()
122 emacsSerial += 1
123 let serial = emacsSerial
124 emacsTask = Task {
125 await work()
126 if emacsSerial == serial { emacsTask = nil }
127 }
128 }
129
130 /// An app command from a menu, run by the main window.
131 private(set) var runRequest: (id: String, serial: Int)?
132 private var runSerial = 0
133
134 func run(_ id: String) {
135 runSerial += 1
136 runRequest = (id, runSerial)
137 }
138
139 /// A capture waiting for the capture window: the template key and the link properties for
140 /// its escapes (org-protocol), or the agenda day to schedule the entry on.
141 var captureRequest: (template: String?, properties: [String: String], day: Int?, serial: Int)?
142 private var captureSerial = 0
143
144 /// Capture from an agenda day, as `org-agenda-capture`: that day is the capture's date, and
145 /// the entry is scheduled on it. The caller opens the capture window.
146 func capture(on day: Int) {
147 captureSerial += 1
148 captureRequest = (nil, [:], day, captureSerial)
149 }
150
151 /// `org-protocol://capture` and `store-link`, and the widgets' `orgstar://` links.
152 func handle(protocolURL url: String) {
153 if let link = URL(string: url).flatMap(AppLink.init(url:)) {
154 switch link {
155 case .agenda: run("app.agenda")
156 case .clock: run("app.clock.goto")
157 case .entry(let path, let offset): jump(path: path, offset: offset)
158 case .capture(let template):
159 captureSerial += 1
160 captureRequest = (template, [:], nil, captureSerial)
161 run("app.capture")
162 }
163 return
164 }
165 switch OrgProtocol.parse(url) {
166 case .capture(let template, let properties):
167 captureSerial += 1
168 captureRequest = (template, properties, nil, captureSerial)
169 run("app.capture")
170 case .storeLink(let link, let title):
171 storeLink(StoredLink(link: link, description: title))
172 NSPasteboard.general.clearContents()
173 NSPasteboard.general.setString(link, forType: .string)
174 case nil:
175 show(String(localized: "orgstar handles org-protocol capture and store-link"))
176 }
177 }
178
179 func jump(path: String, offset: Int) {
180 jumpID += 1
181 jumpRequest = (path, offset, jumpID)
182 }
183
184 func show(_ text: String) {
185 message = text
186 messages.append(text)
187 if messages.count > 100 { messages.removeFirst(messages.count - 100) }
188 AccessibilityNotification.Announcement(text).post()
189 // A local monitor sees an event before it is handled, so a message the key or click
190 // itself shows is set after this clears the last one.
191 if inputMonitor == nil {
192 inputMonitor = NSEvent.addLocalMonitorForEvents(matching: [.keyDown, .leftMouseDown, .rightMouseDown]) { [weak self] event in
193 MainActor.assumeIsolated {
194 if self?.message != nil { self?.message = nil }
195 }
196 return event
197 }
198 }
199 }
200}
201
202struct PromptRequest: Identifiable {
203 let id = UUID()
204 let prompt: Prompt
205 let reply: (String?) -> Void
206}
207
208@MainActor
209final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDelegate {
210 var session: DocumentSession?
211 var commands: AppCommands?
212 #if APPSTORE
213 var workspace: WorkspaceModel?
214 #else
215 let updates = Updates()
216 #endif
217
218 func applicationDidFinishLaunching(_ notification: Notification) {
219 DockIcon.start()
220 if SystemReminderCenter.isAvailable { UNUserNotificationCenter.current().delegate = self }
221 #if !APPSTORE
222 updates.start()
223 #endif
224 }
225
226 #if APPSTORE
227 /// A subscription may have lapsed or renewed while the app was in the background.
228 func applicationDidBecomeActive(_ notification: Notification) {
229 Task { await ProStore.shared.refresh() }
230 }
231 #endif
232
233 /// `:session` interpreters end with the app.
234 func applicationWillTerminate(_ notification: Notification) {
235 #if !APPSTORE
236 BabelSessions.shared.stopAll()
237 #endif
238 }
239
240 /// Reminders show while Orgstar is in front too.
241 nonisolated func userNotificationCenter(
242 _ center: UNUserNotificationCenter, willPresent notification: UNNotification
243 ) async -> UNNotificationPresentationOptions {
244 [.banner, .sound, .list]
245 }
246
247 /// Clicking a reminder shows its entry.
248 nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
249 let info = response.notification.request.content.userInfo
250 guard let path = info["path"] as? String, let offset = info["offset"] as? Int else { return }
251 await MainActor.run {
252 NSApp.activate()
253 commands?.jump(path: path, offset: offset)
254 }
255 }
256
257 /// Files opened from Finder, `open`, or a drop on the Dock icon: each opens as a buffer.
258 /// Ones that arrive before the window is ready wait for it (`pendingOpens`).
259 static var pendingOpens: [String] = []
260
261 func application(_ application: NSApplication, open urls: [URL]) {
262 let paths = urls.filter(\.isFileURL).map(\.path)
263 let links = urls.filter { $0.scheme == "org-protocol" || $0.scheme == AppLink.scheme }.map(\.absoluteString)
264 guard let commands, let session else {
265 Self.pendingOpens += paths
266 Self.pendingLinks += links
267 return
268 }
269 NSApp.activate()
270 for path in paths { session.open(path) }
271 for link in links { commands.handle(protocolURL: link) }
272 }
273
274 /// org-protocol and orgstar:// links that arrive before the window is ready.
275 static var pendingLinks: [String] = []
276
277 /// Files continued from another device before the window is ready.
278 static var pendingHandoffs: [HandoffPlace] = []
279
280 func application(_ application: NSApplication, willContinueUserActivityWithType userActivityType: String) -> Bool {
281 userActivityType == HandoffPlace.activityType
282 }
283
284 /// Handoff from an iPhone, iPad or another Mac.
285 func application(_ application: NSApplication, continue userActivity: NSUserActivity,
286 restorationHandler: @escaping ([any NSUserActivityRestoring]) -> Void) -> Bool {
287 guard userActivity.activityType == HandoffPlace.activityType, let place = HandoffPlace(userInfo: userActivity.userInfo) else { return false }
288 if let handler = commands?.continueHandoff {
289 NSApp.activate()
290 handler(place)
291 } else {
292 Self.pendingHandoffs.append(place)
293 }
294 return true
295 }
296
297 func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true }
298
299 func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
300 guard let session else { return .terminateNow }
301 #if APPSTORE
302 BufferRestore.save(session, workspace: workspace)
303 #else
304 BufferRestore.save(session)
305 #endif
306 guard UnsavedChanges.resolve(session, paths: session.openPaths) else { return .terminateCancel }
307 #if !APPSTORE
308 // Files saved since their folder's last automatic commit are committed before quitting.
309 if GitAutoCommit.shared.hasPending {
310 Task {
311 await GitAutoCommit.shared.flush()
312 sender.reply(toApplicationShouldTerminate: true)
313 }
314 return .terminateLater
315 }
316 #endif
317 return .terminateNow
318 }
319}
320
321/// Unsaved edits when leaving a file or quitting.
322@MainActor
323enum UnsavedChanges {
324 /// Whether the open file can be left: saved in automatic mode, or as the user chooses in
325 /// explicit mode. A save that fails or conflicts keeps the file open.
326 static func resolve(_ session: DocumentSession) -> Bool {
327 guard session.isDirty else { return true }
328 if session.saveMode == .automatic { return session.save() }
329 let alert = NSAlert()
330 alert.messageText = session.path.map { String(localized: "Save changes to \(($0 as NSString).lastPathComponent)?") }
331 ?? String(localized: "Save changes to this file?")
332 alert.informativeText = String(localized: "Your changes will be lost if you don't save them.")
333 alert.addButton(withTitle: String(localized: "Save"))
334 alert.addButton(withTitle: String(localized: "Don't Save"))
335 alert.addButton(withTitle: String(localized: "Cancel"))
336 switch alert.runModal() {
337 case .alertFirstButtonReturn: return session.save()
338 case .alertSecondButtonReturn: return true
339 default: return false
340 }
341 }
342
343 /// Whether the buffers of `paths` can be closed: saved in automatic mode, or as the user
344 /// chooses for all of them in explicit mode.
345 static func resolve(_ session: DocumentSession, paths: [String]) -> Bool {
346 let dirty = paths.filter(session.dirtyPaths.contains)
347 guard !dirty.isEmpty else { return true }
348 if session.saveMode == .automatic { return dirty.map(session.save).allSatisfy { $0 } }
349 if dirty == [session.path] { return resolve(session) }
350 let alert = NSAlert()
351 alert.messageText = String(localized: "Save changes to \(dirty.count) files?")
352 alert.informativeText = dirty.map { ($0 as NSString).lastPathComponent }.joined(separator: ", ")
353 alert.addButton(withTitle: String(localized: "Save All"))
354 alert.addButton(withTitle: String(localized: "Don't Save"))
355 alert.addButton(withTitle: String(localized: "Cancel"))
356 switch alert.runModal() {
357 case .alertFirstButtonReturn: return dirty.map(session.save).allSatisfy { $0 }
358 case .alertSecondButtonReturn: return true
359 default: return false
360 }
361 }
362}
363
364/// The open buffers, their order and carets, kept for the next launch.
365@MainActor
366enum BufferRestore {
367 private static let key = "openBuffers"
368
369 struct State: Codable {
370 var paths: [String]
371 var current: String?
372 var carets: [String: Int]
373 /// In the Mac App Store build, bookmarks of the files outside every folder, which the
374 /// sandbox would otherwise keep orgstar out of after relaunch.
375 var bookmarks: [String: Data]?
376 }
377
378 /// `bookmarking` says which paths get a bookmark. A path still open keeps the bookmark it
379 /// has when no new one is made.
380 static func save(_ session: DocumentSession, bookmarking: (String) -> Bool = { _ in false }, defaults: UserDefaults = .standard) {
381 var carets: [String: Int] = [:]
382 for path in session.openPaths { carets[path] = session.caret(of: path) }
383 let previous = defaults.data(forKey: key).flatMap { try? JSONDecoder().decode(State.self, from: $0) }?.bookmarks ?? [:]
384 var bookmarks: [String: Data] = [:]
385 for path in session.openPaths {
386 bookmarks[path] = (bookmarking(path) ? SecurityBookmark.make(URL(fileURLWithPath: path)) : nil) ?? previous[path]
387 }
388 let state = State(paths: session.openPaths, current: session.path, carets: carets, bookmarks: bookmarks.isEmpty ? nil : bookmarks)
389 if let data = try? JSONEncoder().encode(state) { defaults.set(data, forKey: key) }
390 }
391
392 #if APPSTORE
393 /// Saves with bookmarks for the files outside `workspace`'s folders and grants.
394 static func save(_ session: DocumentSession, workspace: WorkspaceModel?) {
395 save(session, bookmarking: { workspace?.contains(URL(fileURLWithPath: $0)) != true })
396 }
397 #endif
398
399 /// Opens the buffers that were open, in order, and returns the carets to show them at.
400 static func restore(_ session: DocumentSession, defaults: UserDefaults = .standard) -> [String: Int] {
401 guard let data = defaults.data(forKey: key), var state = try? JSONDecoder().decode(State.self, from: data) else { return [:] }
402 // A bookmarked file comes back with access, at the path it has now.
403 for (path, bookmark) in state.bookmarks ?? [:] {
404 guard let moved = SecurityBookmark.resolve(bookmark)?.url.path, moved != path else { continue }
405 state.paths = state.paths.map { $0 == path ? moved : $0 }
406 if state.current == path { state.current = moved }
407 state.carets[moved] = state.carets.removeValue(forKey: path)
408 }
409 let existing = state.paths.filter { FileManager.default.fileExists(atPath: $0) }
410 for path in existing { session.open(path) }
411 if let current = state.current, existing.contains(current) { session.open(current) }
412 return state.carets
413 }
414}
415
416@main
417struct OrgstarApp: App {
418 @NSApplicationDelegateAdaptor private var delegate: AppDelegate
419 @State private var workspace = Result {
420 try WorkspaceModel(directory: WorkspaceModel.defaultDirectory, settings: .with(todoKeywords: Preferences.orgSettings))
421 }
422 @State private var commands = AppCommands()
423 @State private var clock = ClockModel()
424 @State private var scheduler = SystemReminderCenter.isAvailable ? ReminderScheduler(center: SystemReminderCenter()) : nil
425 @State private var session: DocumentSession = {
426 let session = DocumentSession()
427 session.defaults = Preferences.orgSettings
428 return session
429 }()
430
431 init() {
432 PDFExport.mathJaxURL = OrgMathJax.script
433 DiagramBlocks.vizURL = OrgMathJax.viz
434 DiagramBlocks.mermaidURL = OrgMathJax.mermaid
435 #if APPSTORE
436 AgendaSnapshot.useGroupContainer = true
437 EmacsFallback.offered = false
438 _ = FolderGrants.shared
439 ProStore.shared.start()
440 #else
441 DocumentSession.programs = Programs()
442 MacPro.resolve()
443 MacPro.renewInBackground()
444 #endif
445 // `org-sbe` in table formulas runs blocks, so it needs Babel as source blocks do.
446 TableBlocks.allowed = { ProAccess.isUnlockedNow }
447 // Debug builds, and runs with ORGSTAR_PERF set: main-thread stalls in the console.
448 #if DEBUG
449 Perf.watchMainThread()
450 #else
451 if ProcessInfo.processInfo.environment["ORGSTAR_PERF"] != nil { Perf.watchMainThread() }
452 #endif
453 }
454
455 var body: some Scene {
456 Window("orgstar", id: "main") {
457 switch workspace {
458 case .success(let model):
459 ContentView(workspace: model, session: session, commands: commands, scheduler: scheduler, clock: clock)
460 .environment(\.orgTheme, ConfigSync.shared.theme)
461 .tint(ConfigSync.shared.theme.color("accent"))
462 .onAppear {
463 delegate.session = session
464 delegate.commands = commands
465 #if APPSTORE
466 delegate.workspace = model
467 #else
468 GitAutoCommit.shared.roots = { model.rootPaths }
469 GitAutoCommit.shared.report = { commands.show($0) }
470 session.fileWritten = { GitAutoCommit.shared.fileWritten($0) }
471 #endif
472 CaptureIntent.environment = (model, session, clock, commands)
473 }
474 case .failure(let error):
475 ContentUnavailableView("Can't Open the Index", systemImage: "exclamationmark.triangle", description: Text(error.localizedDescription))
476 }
477 }
478 .defaultSize(width: 1280, height: 860)
479 WindowGroup("Editor", id: "editor") {
480 if case .success = workspace {
481 EditorWindowView(session: session, commands: commands)
482 .environment(\.orgTheme, ConfigSync.shared.theme)
483 .tint(ConfigSync.shared.theme.color("accent"))
484 }
485 }
486 .defaultSize(width: 900, height: 700)
487 .commandsRemoved()
488 Window("Agenda", id: "agenda") {
489 if case .success(let model) = workspace {
490 AgendaView(workspace: model, session: session, commands: commands, scheduler: scheduler, clock: clock)
491 .environment(\.orgTheme, ConfigSync.shared.theme)
492 .tint(ConfigSync.shared.theme.color("accent"))
493 }
494 }
495 .defaultSize(width: 760, height: 720)
496 Window("Board", id: "board") {
497 if case .success(let model) = workspace {
498 BoardView(workspace: model, session: session, commands: commands)
499 .environment(\.orgTheme, ConfigSync.shared.theme)
500 .tint(ConfigSync.shared.theme.color("accent"))
501 }
502 }
503 .defaultSize(width: 1100, height: 700)
504 Window("Node Graph", id: "graph") {
505 if case .success(let model) = workspace {
506 RoamGraphWindow(workspace: model, session: session, commands: commands)
507 .tint(ConfigSync.shared.theme.color("accent"))
508 }
509 }
510 .defaultSize(width: 900, height: 700)
511 Window("Clock Report", id: "clock-report") {
512 if case .success(let model) = workspace {
513 ClockReportView(workspace: model, session: session)
514 .environment(\.orgTheme, ConfigSync.shared.theme)
515 .tint(ConfigSync.shared.theme.color("accent"))
516 }
517 }
518 .defaultSize(width: 860, height: 560)
519 Window("Capture", id: "capture") {
520 if case .success(let model) = workspace {
521 CaptureView(workspace: model, session: session, commands: commands, clock: clock)
522 .environment(\.orgTheme, ConfigSync.shared.theme)
523 .tint(ConfigSync.shared.theme.color("accent"))
524 }
525 }
526 .windowResizability(.contentSize)
527 .windowLevel(.floating)
528 .commands {
529 CommandGroup(after: .newItem) {
530 Button("Add Folder…") { commands.showingFolderPicker = true }
531 .keyboardShortcut("o", modifiers: [.command, .shift])
532 Button("Quick Open…") { commands.showingQuickOpen = true }
533 .keyboardShortcut("p")
534 Button("Command Palette…") { commands.showingPalette = true }
535 .keyboardShortcut("p", modifiers: [.command, .shift])
536 }
537 CommandGroup(after: .saveItem) {
538 Menu("Export") {
539 ForEach(EditorCommands.all.filter { $0.id.hasPrefix("app.export.") && !hiddenCommandIDs.contains($0.id) }, id: \.id) { command in
540 Button(command.localizedTitle) { commands.run(command.id) }
541 }
542 }
543 .disabled(session.path == nil)
544 Menu("Publish") {
545 ForEach(EditorCommands.all.filter { $0.id.hasPrefix("app.publish") }, id: \.id) { command in
546 Button(command.localizedTitle) { commands.run(command.id) }
547 }
548 }
549 Divider()
550 Button("Revert to File on Disk") { commands.run("app.revert") }
551 .disabled(session.path == nil)
552 Button("Resolve Sync Conflicts…") { commands.run("app.sync-conflicts") }
553 .disabled(session.path == nil)
554 Button("History…") { commands.run("app.recovery") }
555 .disabled(session.path == nil)
556 Button("Lint File") { commands.run("app.lint") }
557 .disabled(!FileLint.applies(to: session.path))
558 }
559 CommandGroup(replacing: .saveItem) {
560 Button("Close Buffer") {
561 // ⌘W closes the buffer in the main window, and other windows themselves.
562 if let key = NSApp.keyWindow, key.identifier?.rawValue.contains("main") != true {
563 key.performClose(nil)
564 } else {
565 commands.run("app.buffer.kill")
566 }
567 }
568 .keyboardShortcut("w")
569 Button("Close Window") { NSApp.keyWindow?.performClose(nil) }
570 .keyboardShortcut("w", modifiers: [.command, .shift])
571 Divider()
572 Button("Save") {
573 if !session.save(), session.conflict != nil { commands.showingConflict = true }
574 }
575 .keyboardShortcut("s")
576 .disabled(session.path == nil || session.isReadOnly)
577 Button("Save All") { commands.run("app.save-all") }
578 .keyboardShortcut("s", modifiers: [.command, .option])
579 .disabled(session.dirtyPaths.isEmpty)
580 }
581 CommandGroup(after: .sidebar) {
582 Button("Split Pane Below") { commands.run("app.split-below") }
583 .keyboardShortcut("2", modifiers: [.command, .control])
584 Button("Split Pane Right") { commands.run("app.split-right") }
585 .keyboardShortcut("3", modifiers: [.command, .control])
586 Button("Close Pane") { commands.run("app.pane-close") }
587 .keyboardShortcut("0", modifiers: [.command, .control])
588 Button("Close Other Panes") { commands.run("app.pane-only") }
589 .keyboardShortcut("1", modifiers: [.command, .control])
590 Button("Next Pane") { commands.run("app.pane-next") }
591 .keyboardShortcut("`", modifiers: [.command, .option])
592 Divider()
593 ViewMenuToggles(commands: commands)
594 Divider()
595 Button("Messages") { commands.run("app.messages") }
596 }
597 CommandGroup(after: .pasteboard) {
598 Divider()
599 FindMenu(commands: commands)
600 MacroMenu(commands: commands)
601 }
602 CommandGroup(after: .textEditing) {
603 Button("Cancel Running Task") { commands.run("app.babel.cancel") }
604 .keyboardShortcut(".")
605 .disabled(!session.isRunningBabel && commands.emacsTask == nil)
606 Button("Search Notes") { commands.focusSearch = true }
607 .keyboardShortcut("f", modifiers: [.command, .shift])
608 }
609 CommandGroup(before: .windowList) {
610 AgendaMenuItem()
611 Divider()
612 Button("Switch to Buffer…") { commands.run("app.buffer.switch") }
613 Button("Next Buffer") { commands.run("app.buffer.next") }
614 .keyboardShortcut("]", modifiers: [.command, .shift])
615 Button("Previous Buffer") { commands.run("app.buffer.previous") }
616 .keyboardShortcut("[", modifiers: [.command, .shift])
617 Divider()
618 }
619 CommandGroup(after: .newItem) {
620 Button("Capture…") { commands.run("app.capture") }
621 .keyboardShortcut("n", modifiers: [.command, .shift])
622 Button("New File from Template…") { commands.run("app.new-file-from-template") }
623 Button("New Window") { commands.run("app.window-new") }
624 .keyboardShortcut("n", modifiers: [.command, .option])
625 }
626 }
627 .commands {
628 CommandMenu("Org") {
629 ClockMenu(commands: commands, clock: clock)
630 Divider()
631 OrgMenuItems(commands: commands)
632 }
633 }
634 .commands {
635 CommandGroup(after: .appSettings) {
636 Button("Edit Config File") { commands.jump(path: UserConfig.configFile.path, offset: 0) }
637 .keyboardShortcut(",", modifiers: [.command, .option])
638 }
639 #if !APPSTORE
640 CommandGroup(after: .appInfo) {
641 CheckForUpdatesItem(updates: delegate.updates)
642 }
643 #endif
644 CommandGroup(replacing: .help) {
645 Button("orgstar Manual") { NSWorkspace.shared.open(Manual.home) }
646 Button("Keys") { NSWorkspace.shared.open(Manual.keys) }
647 Divider()
648 Button("What's New in orgstar") { commands.whatsNew = WhatsNew.releases.first }
649 .disabled(!commands.mainWindowOpen)
650 }
651 }
652 Settings {
653 #if APPSTORE
654 SettingsView(commands: commands, workspace: try? workspace.get())
655 #else
656 SettingsView(commands: commands, workspace: try? workspace.get(), updates: delegate.updates)
657 #endif
658 }
659 }
660}
661
662/// The Org menu: every org command and the app's commands for entries and notes, in submenus by
663/// subject, with the keys that run them in the current keymap.
664struct OrgMenuItems: View {
665 let commands: AppCommands
666
667 /// Submenus and the command id prefixes they hold, in menu order. A command goes in the
668 /// first submenu with a prefix it starts with.
669 static let groups: [(title: LocalizedStringKey, prefixes: [String])] = [
670 ("Visibility", ["org.cycle", "org.fold.", "org.narrow.", "org.widen", "org.sparse-tree", "org.toggle-inline-images", "org.latex-preview"]),
671 ("Headings", ["org.heading.", "org.subtree.", "org.element.", "org.goto", "org.sort", "org.archive.", "app.refile", "app.archive"]),
672 ("TODO and Tags", ["org.todo.", "org.priority.", "org.tags.", "org.effort.", "app.rename-"]),
673 ("Properties and Columns", ["org.property.", "org.columns", "org.drawer."]),
674 ("Dates and Timers", ["org.schedule", "org.deadline", "org.timestamp.", "org.timer."]),
675 ("Lists", ["org.item.", "org.checkbox."]),
676 ("Tables", ["org.table", "app.table-", "app.plot"]),
677 ("Links and Footnotes", ["org.link.", "org.id.", "org.footnote."]),
678 ("Blocks", ["org.babel.", "org.structure-template", "org.edit-special", "org.dblock.", "org.clock.report", "org.denote."]),
679 ("Text", ["org.emphasize", "org.fill-"]),
680 ("Attachments", ["app.attach."]),
681 ("Notes", ["app.dailies.", "app.node."]),
682 ("Encryption", ["app.crypt."]),
683 ]
684
685 private static func group(of id: String) -> Int? {
686 groups.firstIndex { $0.prefixes.contains { id.hasPrefix($0) } }
687 }
688
689 private static let shown = EditorCommands.all.filter { ($0.id.hasPrefix("org.") || group(of: $0.id) != nil) && !hiddenCommandIDs.contains($0.id) }
690
691 var body: some View {
692 // Commands that fit no subject, such as Act at Point, come first.
693 ForEach(Self.shown.filter { Self.group(of: $0.id) == nil }, id: \.id) { item($0) }
694 Divider()
695 ForEach(Self.groups.indices, id: \.self) { index in
696 Menu(Self.groups[index].title) {
697 ForEach(Self.shown.filter { Self.group(of: $0.id) == index }, id: \.id) { item($0) }
698 }
699 }
700 }
701
702 private func item(_ command: EditorCommand) -> some View {
703 Button {
704 if command.id.hasPrefix("org.") { commands.editor?.run(command.id) } else { commands.run(command.id) }
705 } label: {
706 Text(command.localizedTitle)
707 if let keys = commands.keyLabel(for: command.id) { Text(keys) }
708 }
709 .disabled(command.id.hasPrefix("org.") && commands.editor == nil)
710 }
711}
712
713/// The user manual, as `scripts/publish-docs.sh` publishes it.
714enum Manual {
715 static let home = URL(string: "https://files.krz.sh/orgstar/")!
716 /// The key reference, with every preset's keys.
717 static let keys = URL(string: "https://files.krz.sh/orgstar/guide/03-keys.html#key-reference")!
718}
719
720/// View ▸ the panes and the focused editor's modes, checked while on.
721struct ViewMenuToggles: View {
722 let commands: AppCommands
723 @AppStorage("backlinksShown") private var backlinksShown = true
724 @AppStorage("inspectorShown") private var inspectorShown = false
725
726 var body: some View {
727 let outline = commands.outlineShown
728 let editor = commands.editor
729 // A key that switches an editor mode shows a message, so the checks follow it.
730 let _ = commands.message
731 Toggle("Show Outline", isOn: Binding(get: { outline }, set: { _ in commands.run("app.toggle-outline") }))
732 .keyboardShortcut("o", modifiers: [.command, .option])
733 Toggle("Show Backlinks", isOn: $backlinksShown)
734 Toggle("Show Inspector", isOn: $inspectorShown)
735 .keyboardShortcut("i", modifiers: [.command, .option])
736 MarkupToggle()
737 editorToggle("Truncate Long Lines", "editor.toggle-truncate-lines", editor?.truncatesLines)
738 editorToggle("Auto Fill", "editor.toggle-auto-fill", editor?.autoFills)
739 editorToggle("Check Spelling While Typing", "editor.toggle-spell-check", editor?.spellChecking)
740 }
741
742 private func editorToggle(_ title: LocalizedStringKey, _ id: String, _ on: Bool?) -> some View {
743 Toggle(title, isOn: Binding(get: { on ?? false }, set: { _ in commands.editor?.run(id) }))
744 .disabled(on == nil)
745 }
746}
747
748/// View ▸ Show Markup (link brackets and targets, emphasis markers) and Show Line Numbers.
749struct MarkupToggle: View {
750 @AppStorage("showTabBar") private var showTabBar = false
751 @AppStorage("showMarkup") private var showMarkup = false
752 @AppStorage("showLineNumbers") private var showLineNumbers = false
753 @AppStorage("lineNumbersType") private var lineNumbersType = "t"
754
755 var body: some View {
756 Toggle("Show Markup", isOn: $showMarkup)
757 .keyboardShortcut("m", modifiers: [.command, .shift])
758 Toggle("Show Line Numbers", isOn: $showLineNumbers)
759 .keyboardShortcut("l", modifiers: [.command, .shift])
760 Picker("Line Numbers", selection: $lineNumbersType) {
761 Text("Absolute").tag("t")
762 Text("Relative").tag("relative")
763 Text("Visual").tag("visual")
764 }
765 Toggle("Show Tab Bar", isOn: $showTabBar)
766 }
767}
768
769/// Edit ▸ Find: the editor's find bar.
770struct FindMenu: View {
771 let commands: AppCommands
772
773 var body: some View {
774 Menu("Find") {
775 item("Find…", "edit.find", "f")
776 item("Find and Replace…", "edit.replace", "f", [.command, .option])
777 item("Find Next", "edit.find-next", "g")
778 item("Find Previous", "edit.find-previous", "g", [.command, .shift])
779 item("Use Selection for Find", "edit.use-selection-for-find", "e")
780 Divider()
781 Button("Replace in Files…") { commands.run("app.replace-in-files") }
782 .keyboardShortcut("f", modifiers: [.command, .option, .shift])
783 }
784 }
785
786 private func item(_ title: String, _ id: String, _ key: KeyEquivalent, _ modifiers: EventModifiers = .command) -> some View {
787 Button(title) { commands.editor?.run(id) }
788 .keyboardShortcut(key, modifiers: modifiers)
789 .disabled(commands.editor == nil)
790 }
791}
792
793/// Edit ▸ Macros: keyboard macros, with the keys that run them in the current keymap.
794struct MacroMenu: View {
795 let commands: AppCommands
796
797 var body: some View {
798 Menu("Macros") {
799 item("Start Recording", "macro.start")
800 item("Stop Recording", "macro.end")
801 item("Run Last Macro", "macro.call")
802 Divider()
803 item("Name Last Macro…", "macro.name")
804 item("Run Macro…", "macro.run")
805 }
806 }
807
808 private func item(_ title: LocalizedStringKey, _ id: String) -> some View {
809 Button {
810 commands.editor?.run(id)
811 } label: {
812 Text(title)
813 if let keys = commands.keyLabel(for: id) { Text(keys) }
814 }
815 .disabled(commands.editor == nil)
816 }
817}
818
819/// Window ▸ Agenda.
820struct AgendaMenuItem: View {
821 @Environment(\.openWindow) private var openWindow
822
823 var body: some View {
824 Button("Agenda") { openWindow(id: "agenda") }
825 .keyboardShortcut("a", modifiers: [.command, .shift])
826 Button("Board") { openWindow(id: "board") }
827 .keyboardShortcut("b", modifiers: [.command, .shift])
828 Button("Graph") { if ProAccess.shared.allows(.roam) { openWindow(id: "graph") } }
829 }
830}
831
832struct SettingsView: View {
833 let commands: AppCommands
834 let workspace: WorkspaceModel?
835 #if !APPSTORE
836 let updates: Updates
837 #endif
838 @State private var importing = false
839 #if APPSTORE
840 @State private var configFolder = UserConfig.directoryOverride
841 #endif
842 @Environment(\.openWindow) private var openWindow
843 @AppStorage("saveMode") private var saveMode = SaveMode.automatic
844 @AppStorage("keymap") private var preset = KeymapPreset.emacs
845 @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
846 @AppStorage("tagsColumn") private var tagsColumn = -77
847 @AppStorage("headingAfterSubtree") private var headingAfterSubtree = false
848 @AppStorage("splitLine") private var splitLine = false
849 @AppStorage("alphabeticalLists") private var alphabeticalLists = true
850 @AppStorage("fillColumn") private var fillColumn = 80
851 @AppStorage("hiddenMarkers") private var hiddenMarkers = true
852 @AppStorage("prettyEntities") private var prettyEntities = true
853 @AppStorage("startupTruncated") private var startupTruncated = false
854 @AppStorage("todoKeywords") private var todoKeywords = Preferences.defaultTodoKeywords
855 @AppStorage("logDone") private var logDone = "nil"
856 @AppStorage("logIntoDrawer") private var logIntoDrawer = ""
857 @AppStorage("useSpeedCommands") private var useSpeedCommands = false
858 @AppStorage("spellCheck") private var spellCheck = false
859 @AppStorage("completionAuto") private var completionAuto = "preset"
860 @AppStorage("completionAutoDelay") private var completionAutoDelay = 400
861 @AppStorage("completionAutoPrefix") private var completionAutoPrefix = 2
862 @AppStorage("completionStyle") private var completionStyle = "preset"
863 @AppStorage("completionWords") private var completionWords = false
864 @AppStorage("enforceTodoDependencies") private var enforceTodoDependencies = false
865 @AppStorage("enforceTodoCheckboxDependencies") private var enforceTodoCheckboxDependencies = false
866 @AppStorage("agendaSpan") private var agendaSpan = 10
867 @AppStorage("agendaStartOffset") private var agendaStartOffset = 0
868 @AppStorage("agendaSubfolders") private var agendaSubfolders = false
869 @AppStorage("agendaShowAllDates") private var agendaShowAllDates = false
870 @AppStorage("habitsOnlyForToday") private var habitsOnlyForToday = true
871 @AppStorage("agendaDimBlockedTasks") private var agendaDimBlockedTasks = "t"
872 @AppStorage("calendarEvents") private var calendarEvents = false
873 @AppStorage("calendarEventCalendars") private var calendarEventCalendars = ""
874 @State private var calendars: [(id: String, title: String, color: RGBA?)] = []
875 @AppStorage("agendaReminders") private var agendaReminders = false
876 @AppStorage("agendaReminderLists") private var agendaReminderLists = ""
877 @State private var reminderLists: [(id: String, title: String, color: RGBA?)] = []
878 @AppStorage("reminders") private var reminders = true
879 @AppStorage("reminderLead") private var reminderLead = 12
880 @AppStorage("clockIdleTime") private var clockIdleTime = 0
881 @AppStorage("clockHistoryLength") private var clockHistoryLength = 5
882 @AppStorage("globalCapture") private var globalCapture = true
883 @AppStorage("menuBarItem") private var menuBarItem = false
884 @AppStorage("settingsTab") private var tab = "general"
885 @AppStorage("showHiddenFiles") private var showHiddenFiles = true
886 @AppStorage("themeFont") private var themeFont = ""
887 @AppStorage("themeBodyFont") private var themeBodyFont = ""
888 @AppStorage("themeFontSize") private var themeFontSize = 13
889 @AppStorage("themeLineSpacing") private var themeLineSpacing = 2
890 @AppStorage("themeTextWidth") private var themeTextWidth = 0
891 @AppStorage("themeHeadingStep") private var themeHeadingStep = 1
892
893 /// Installed font families that aren't monospaced, for body text.
894 private static let proportionalFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in
895 NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == false
896 }
897
898 /// Installed monospaced font families.
899 private static let monospacedFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in
900 NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == true
901 }
902
903 var body: some View {
904 TabView(selection: $tab) {
905 Tab("General", systemImage: "gearshape", value: "general") { general }
906 Tab("Editing", systemImage: "text.alignleft", value: "editing") { editing }
907 Tab("Appearance", systemImage: "paintpalette", value: "appearance") { appearance }
908 Tab("Agenda", systemImage: "calendar", value: "agenda") { agenda }
909 Tab("Capture", systemImage: "tray.and.arrow.down", value: "capture") { capture }
910 #if !APPSTORE
911 Tab(value: "git") { GitSettingsForm(workspace: workspace) } label: {
912 Label { Text("Git", tableName: "DeveloperID") } icon: { Image(systemName: "arrow.triangle.branch") }
913 }
914 #endif
915 #if APPSTORE
916 Tab("orgstar+", systemImage: "star", value: "pro") { StoreForm() }
917 #else
918 Tab("orgstar+", systemImage: "star", value: "pro") { LicenseForm() }
919 #endif
920 }
921 .frame(width: 600)
922 }
923
924 private func editConfig() {
925 ConfigSync.shared.start()
926 openWindow(id: "main")
927 commands.jump(path: UserConfig.configFile.path, offset: 0)
928 }
929
930 #if APPSTORE
931 /// A folder outside the app's container, such as `~/.config/orgstar` kept with dotfiles.
932 private func chooseConfigFolder() {
933 let panel = NSOpenPanel()
934 panel.canChooseFiles = false
935 panel.canChooseDirectories = true
936 panel.canCreateDirectories = true
937 panel.directoryURL = configFolder ?? ConfigFolder.suggested
938 panel.message = String(localized: "Choose the folder for config.toml and orgstar's other configuration files.", comment: "Choose Configuration Folder panel")
939 guard panel.runModal() == .OK, let url = panel.url else { return }
940 if !ConfigFolder.set(url) {
941 GrantAccess.tell(String(localized: "orgstar can't keep \(OrgPaths.abbreviatingWithTilde(url.path)) as the configuration folder.", comment: "Alert when the chosen configuration folder can't be saved"),
942 String(localized: "Access lasts until orgstar quits.", comment: "Alert when a folder grant or the configuration folder can't be saved"))
943 }
944 useConfigFolder(url)
945 }
946
947 /// Reads and writes the configuration in `url`, or with nil in the default folder.
948 private func useConfigFolder(_ url: URL?) {
949 if url == nil { ConfigFolder.clear() }
950 UserConfig.directoryOverride = url
951 configFolder = url
952 ConfigSync.shared.move(to: UserConfig.configFile)
953 }
954 #endif
955
956 private var general: some View {
957 Form {
958 Section {
959 LabeledContent("config.toml") {
960 HStack {
961 Button("Edit in orgstar") { editConfig() }
962 Button("Open with Default App") { NSWorkspace.shared.open(UserConfig.configFile) }
963 Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([UserConfig.configFile]) }
964 }
965 }
966 #if APPSTORE
967 LabeledContent("Folder") {
968 HStack {
969 Button("Choose Configuration Folder…") { chooseConfigFolder() }
970 if configFolder != nil { Button("Use Default Folder") { useConfigFolder(nil) } }
971 }
972 }
973 #endif
974 LabeledContent("Emacs") {
975 Button("Import from Emacs…") { importing = true }
976 }
977 } footer: {
978 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.")
979 .settingsFooter()
980 }
981 #if !APPSTORE
982 if updates.canCheck {
983 Section {
984 Toggle(isOn: Binding(get: { updates.automatically }, set: { updates.automatically = $0 })) { Text("Check for updates automatically", tableName: "DeveloperID") }
985 } footer: {
986 Text("Once a day, from the app's own feed. orgstar ▸ Check for Updates… checks now.", tableName: "DeveloperID")
987 .settingsFooter()
988 }
989 }
990 #endif
991 Section {
992 Picker("Save files", selection: $saveMode) {
993 Text("Automatically, when typing stops").tag(SaveMode.automatic)
994 Text("Only with File ▸ Save (⌘S)").tag(SaveMode.explicit)
995 }
996 .pickerStyle(.radioGroup)
997 }
998 Section {
999 Picker("Keys", selection: $preset) {
1000 ForEach(KeymapPreset.allCases, id: \.self) { Text($0.title).tag($0) }
1001 }
1002 Toggle("Show hidden files and folders", isOn: $showHiddenFiles)
1003 Toggle("Keep orgstar in the menu bar", isOn: $menuBarItem)
1004 .help("Capture, the agenda, today's entries and the clock, from any app. When off, the menu bar shows orgstar only while a clock runs.")
1005 Picker("Option as Meta", selection: $optionAsMeta) {
1006 Text("Left Option").tag(OptionAsMeta.left.rawValue)
1007 Text("Right Option").tag(OptionAsMeta.right.rawValue)
1008 Text("Both").tag(OptionAsMeta([.left, .right]).rawValue)
1009 Text("Neither").tag(0)
1010 }
1011 } footer: {
1012 Text("Your own bindings go in \(KeymapLoader.userFile.path), on top of the preset.")
1013 .settingsFooter()
1014 }
1015 }
1016 .formStyle(.grouped)
1017 .frame(height: 330)
1018 .sheet(isPresented: $importing) { EmacsImportView(workspace: workspace) }
1019 }
1020
1021 private var editing: some View {
1022 Form {
1023 Section {
1024 Picker("Tags", selection: $tagsColumn) {
1025 Text("Aligned to end at column 77").tag(-77)
1026 Text("One space after the title").tag(0)
1027 }
1028 .help(Text(verbatim: "org-tags-column"))
1029 Toggle(isOn: $headingAfterSubtree) { keyed("New headings go after the subtree", "org.heading.insert") }
1030 .help(Text(verbatim: "org-insert-heading-respect-content"))
1031 Toggle(isOn: $splitLine) { keyed("New headings and items split the line at the caret", "org.heading.insert") }
1032 .help(Text(verbatim: "org-M-RET-may-split-line"))
1033 Toggle("Lists can use letters (a. b. c.)", isOn: $alphabeticalLists)
1034 .help(Text(verbatim: "org-list-allow-alphabetical"))
1035 Stepper(value: $fillColumn, in: 40...200) { keyed("Fill Paragraph wraps lines at column \(fillColumn)", "org.fill-paragraph") }
1036 .help(Text(verbatim: "fill-column"))
1037 }
1038 Section {
1039 Toggle("Long lines run off the edge instead of wrapping", isOn: $startupTruncated)
1040 .help(Text(verbatim: "org-startup-truncated"))
1041 } footer: {
1042 Text("Applies to files as they open. View ▸ Truncate Long Lines switches the current file.")
1043 .settingsFooter()
1044 }
1045 Section {
1046 Toggle("Emacs hides emphasis markers", isOn: $hiddenMarkers)
1047 .help(Text(verbatim: "org-hide-emphasis-markers"))
1048 Toggle("Emacs shows entities as characters", isOn: $prettyEntities)
1049 .help(Text(verbatim: "org-pretty-entities"))
1050 } footer: {
1051 Text("Tags, tables and Fill Paragraph measure text as your Emacs displays it, so both write the same file.")
1052 .settingsFooter()
1053 }
1054 Section {
1055 TextField("Default TODO keywords", text: $todoKeywords, axis: .vertical)
1056 } footer: {
1057 Text("For files without #+TODO, in #+TODO syntax, one sequence per line. Takes effect when orgstar restarts.")
1058 .settingsFooter()
1059 }
1060 Section {
1061 Toggle("Entries can't be done before their TODO children", isOn: $enforceTodoDependencies)
1062 .help(Text(verbatim: "org-enforce-todo-dependencies"))
1063 Toggle("Entries can't be done with unchecked boxes", isOn: $enforceTodoCheckboxDependencies)
1064 .help(Text(verbatim: "org-enforce-todo-checkbox-dependencies"))
1065 } footer: {
1066 Text("Under a parent with the ORDERED property (Org ▸ Properties and Columns ▸ Toggle ORDERED Property), TODO children are also done in order.")
1067 .settingsFooter()
1068 }
1069 Section {
1070 Picker("When an entry is done", selection: $logDone) {
1071 Text("Record nothing").tag("nil")
1072 Text("Record the time, as CLOSED").tag("time")
1073 Text("Record the time and ask for a note").tag("note")
1074 }
1075 .help(Text(verbatim: "org-log-done"))
1076 Toggle("State notes go in a LOGBOOK drawer", isOn: logIntoDrawerOn)
1077 .help(Text(verbatim: "org-log-into-drawer"))
1078 } footer: {
1079 Text("Keyword flags such as DONE(d!) and #+STARTUP words in a file override these. org-log-reschedule and org-log-redeadline are in config.toml.")
1080 .settingsFooter()
1081 }
1082 Section {
1083 Toggle("Speed keys: single letters at the start of a heading line run commands", isOn: $useSpeedCommands)
1084 .help(Text(verbatim: "org-use-speed-commands"))
1085 Toggle("Check spelling while typing", isOn: $spellCheck)
1086 .help(Text(verbatim: "spell-check"))
1087 } footer: {
1088 Text("Spell checking applies to files as they open; Check Spelling While Typing switches the current file. Code, links, dates, tags and keywords aren't checked.")
1089 .settingsFooter()
1090 }
1091 Section {
1092 Picker("Completion list opens", selection: $completionAuto) {
1093 Text("As the keys do (by itself with Doom)").tag("preset")
1094 Text("By itself as you type").tag("on")
1095 Text("Only with a key").tag("off")
1096 }
1097 .help(Text(verbatim: "completion-auto"))
1098 Stepper("After a pause of \(completionAutoDelay) ms", value: $completionAutoDelay, in: 0...2000, step: 50)
1099 .help(Text(verbatim: "completion-auto-delay"))
1100 Stepper("Once \(completionAutoPrefix) characters are typed", value: $completionAutoPrefix, in: 1...10)
1101 .help(Text(verbatim: "completion-auto-prefix"))
1102 Picker("Candidates", selection: $completionStyle) {
1103 Text("As the keys do (letters in order with Doom)").tag("preset")
1104 Text("Start with what's typed").tag("prefix")
1105 Text("Have its letters in order, best first").tag("fuzzy")
1106 }
1107 .help(Text(verbatim: "completion-style"))
1108 Toggle("The list offers words from open files and folders", isOn: $completionWords)
1109 .help(Text(verbatim: "completion-words"))
1110 } header: {
1111 Text("Completion")
1112 } footer: {
1113 Text("Doom's keys open the list by itself and match letters in order, as Doom's corfu does; the Emacs and Mac keys do neither unless set here. Expand Word completes the word before the caret from your files whatever is set.")
1114 .settingsFooter()
1115 }
1116 }
1117 .formStyle(.grouped)
1118 .frame(height: 860)
1119 }
1120
1121 /// `label`, then the keys that run `command` in the current preset, if any.
1122 private func keyed(_ label: LocalizedStringKey, _ command: String) -> some View {
1123 HStack(spacing: 6) {
1124 Text(label)
1125 if let keys = commands.keyLabel(for: command) {
1126 Text(verbatim: keys).font(.system(.body, design: .monospaced)).foregroundStyle(.secondary)
1127 }
1128 }
1129 }
1130
1131 /// `org-log-into-drawer` as a switch: on is "LOGBOOK" (Emacs's t); a drawer name of its own counts as on.
1132 private var logIntoDrawerOn: Binding<Bool> {
1133 Binding(get: { !logIntoDrawer.isEmpty }, set: { logIntoDrawer = $0 ? "LOGBOOK" : "" })
1134 }
1135
1136 private var appearance: some View {
1137 Form {
1138 ThemePickerSection()
1139 AppIconSection()
1140 Section {
1141 Picker("Font", selection: $themeFont) {
1142 Text("System monospaced").tag("")
1143 Divider()
1144 ForEach(Self.monospacedFamilies, id: \.self) { Text($0).tag($0) }
1145 if !themeFont.isEmpty, !Self.monospacedFamilies.contains(themeFont) { Text(themeFont).tag(themeFont) }
1146 }
1147 Picker("Body font", selection: $themeBodyFont) {
1148 Text("Same as Font").tag("")
1149 Text("System").tag("system")
1150 Divider()
1151 ForEach(Self.proportionalFamilies, id: \.self) { Text($0).tag($0) }
1152 if !["", "system"].contains(themeBodyFont), !Self.proportionalFamilies.contains(themeBodyFont) { Text(themeBodyFont).tag(themeBodyFont) }
1153 }
1154 Stepper("Size: \(themeFontSize) pt", value: $themeFontSize, in: 8...36)
1155 Stepper("Line spacing: \(themeLineSpacing) pt", value: $themeLineSpacing, in: 0...16)
1156 Picker("Text width", selection: $themeTextWidth) {
1157 Text("Whole editor").tag(0)
1158 ForEach([60, 70, 80, 90, 100, 120], id: \.self) { Text("\($0) columns").tag($0) }
1159 if ![0, 60, 70, 80, 90, 100, 120].contains(themeTextWidth) { Text("\(themeTextWidth) columns").tag(themeTextWidth) }
1160 }
1161 Stepper("Headings grow by \(themeHeadingStep) pt a level", value: $themeHeadingStep, in: 0...8)
1162 } footer: {
1163 Text("Tags and tables line up in columns, so Font should be monospaced. With a body font, prose uses it while tables, code, dates, tags and drawers keep Font.")
1164 .settingsFooter()
1165 }
1166 Section {
1167 LabeledContent("Colors") {
1168 HStack {
1169 Button("Edit in config.toml") { editConfig() }
1170 Button("Show Default Theme") {
1171 openWindow(id: "main")
1172 commands.jump(path: UserConfig.directory.appendingPathComponent("default-theme.toml").path, offset: 0)
1173 }
1174 }
1175 }
1176 } footer: {
1177 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.")
1178 .settingsFooter()
1179 }
1180 }
1181 .formStyle(.grouped)
1182 .frame(height: 620)
1183 }
1184
1185 private var agenda: some View {
1186 Form {
1187 Section {
1188 Stepper("Agenda shows \(agendaSpan) days", value: $agendaSpan, in: 1...366)
1189 Stepper(agendaStartOffset == 0 ? "Agenda starts today" : "Agenda starts \(-agendaStartOffset) days before today", value: $agendaStartOffset, in: -14...0)
1190 Toggle("Include files in subfolders", isOn: $agendaSubfolders)
1191 Toggle("Show days without entries", isOn: $agendaShowAllDates)
1192 Toggle("Habits only today", isOn: $habitsOnlyForToday)
1193 Picker("Blocked entries", selection: $agendaDimBlockedTasks) {
1194 Text("Dimmed").tag("t")
1195 Text("Hidden").tag("invisible")
1196 Text("Shown as usual").tag("nil")
1197 }
1198 }
1199 Section {
1200 Toggle("Show events from Calendar", isOn: $calendarEvents)
1201 .disabled(!ProAccess.shared.isUnlocked && !calendarEvents)
1202 .help(ProAccess.shared.isUnlocked ? "" : "Needs orgstar+")
1203 if calendarEvents {
1204 choices(calendars, empty: CalendarEvents.isAuthorized ? "No calendars." : "Allow orgstar to read your calendars in System Settings ▸ Privacy & Security ▸ Calendars.", setting: $calendarEventCalendars)
1205 }
1206 } footer: {
1207 Text("Events show in the agenda; double-click one to open it in Calendar, or choose Edit Event… in its context menu. New calendars show while every calendar is checked.")
1208 .settingsFooter()
1209 }
1210 .task(id: calendarEvents) {
1211 let allowed = calendarEvents ? await CalendarAccess.events.requestAccess() : false
1212 calendars = allowed ? CalendarAccess.events.calendars() : []
1213 }
1214 Section {
1215 Toggle("Show reminders from Reminders", isOn: $agendaReminders)
1216 .disabled(!ProAccess.shared.isUnlocked && !agendaReminders)
1217 .help(ProAccess.shared.isUnlocked ? "" : "Needs orgstar+")
1218 if agendaReminders {
1219 choices(reminderLists, empty: ReminderLists.isAuthorized ? "No lists." : "Allow orgstar to read your reminders in System Settings ▸ Privacy & Security ▸ Reminders.", setting: $agendaReminderLists)
1220 }
1221 } footer: {
1222 Text("Incomplete reminders with a due date show in the agenda read-only, overdue ones under today; double-click one to open it in Reminders.")
1223 .settingsFooter()
1224 }
1225 .task(id: agendaReminders) {
1226 let allowed = agendaReminders ? await CalendarAccess.reminders.requestAccess() : false
1227 reminderLists = allowed ? CalendarAccess.reminders.lists() : []
1228 }
1229 Section {
1230 Toggle("Notify before timed agenda entries", isOn: $reminders)
1231 Stepper("\(reminderLead) minutes before", value: $reminderLead, in: 0...120)
1232 .disabled(!reminders)
1233 } footer: {
1234 Text("An entry's APPT_WARNTIME property overrides the lead time.")
1235 .settingsFooter()
1236 }
1237 Section {
1238 Toggle("Ask what to do with idle time while clocked in", isOn: Binding {
1239 clockIdleTime > 0
1240 } set: { on in
1241 clockIdleTime = on ? 15 : 0
1242 })
1243 Stepper("After \(max(clockIdleTime, 1)) minutes without keyboard or mouse input", value: $clockIdleTime, in: 1...240)
1244 .disabled(clockIdleTime == 0)
1245 Stepper("Remember \(clockHistoryLength) recently clocked entries", value: $clockHistoryLength, in: 1...35)
1246 } footer: {
1247 Text("org-clock-idle-time and org-clock-history-length. Org ▸ Clock lists the recent entries.")
1248 .settingsFooter()
1249 }
1250 }
1251 .formStyle(.grouped)
1252 .frame(height: 560)
1253 }
1254
1255 /// A toggle per calendar or reminder list, with its color; `empty` when there are none.
1256 @ViewBuilder
1257 private func choices(_ calendars: [(id: String, title: String, color: RGBA?)], empty: LocalizedStringKey, setting: Binding<String>) -> some View {
1258 if calendars.isEmpty {
1259 Text(empty)
1260 .foregroundStyle(.secondary)
1261 }
1262 ForEach(calendars, id: \.id) { calendar in
1263 Toggle(isOn: chosen(calendar, among: calendars, setting: setting)) {
1264 HStack(spacing: 6) {
1265 Circle()
1266 .fill(calendar.color.map { Color(.sRGB, red: $0.red, green: $0.green, blue: $0.blue, opacity: $0.alpha) } ?? .secondary)
1267 .frame(width: 8, height: 8)
1268 Text(calendar.title)
1269 }
1270 }
1271 }
1272 }
1273
1274 /// `calendar-event-calendars` and `agenda-reminder-lists`: empty for every calendar or
1275 /// list, else the titles checked.
1276 private func chosen(
1277 _ calendar: (id: String, title: String, color: RGBA?), among calendars: [(id: String, title: String, color: RGBA?)], setting: Binding<String>
1278 ) -> Binding<Bool> {
1279 let chosen = setting.wrappedValue.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
1280 return Binding {
1281 CalendarEvents.chooses(id: calendar.id, title: calendar.title, chosen: chosen)
1282 } set: { on in
1283 var titles = calendars.map(\.title).filter { title in
1284 chosen.isEmpty || chosen.contains(title) || chosen.contains(calendars.first { $0.title == title }?.id ?? "")
1285 }
1286 titles.removeAll { $0 == calendar.title }
1287 if on { titles.append(calendar.title) }
1288 // An empty list means every calendar; turning events off hides them all.
1289 guard !titles.isEmpty else { return }
1290 setting.wrappedValue = Set(titles) == Set(calendars.map(\.title)) ? "" : titles.joined(separator: ", ")
1291 }
1292 }
1293
1294 private var capture: some View {
1295 Form {
1296 Section {
1297 Toggle("⌃⌥Space opens Capture from any app", isOn: $globalCapture)
1298 } footer: {
1299 Text("Templates go in \(CaptureTemplates.userFile.path).")
1300 .settingsFooter()
1301 }
1302 }
1303 .formStyle(.grouped)
1304 .frame(height: 160)
1305 }
1306}
1307
1308extension Text {
1309 func settingsFooter() -> some View {
1310 font(.caption)
1311 .foregroundStyle(.secondary)
1312 .textSelection(.enabled)
1313 .frame(maxWidth: .infinity, alignment: .leading)
1314 }
1315}