Sources/Orgstar/OrgstarApp.swift
1317 lines · 63860 bytes
52 symbols in this file
AppCommandsstoreLinkkeyLabelaskanswerrunInEmacsruncapturehandlejumpshowPromptRequestAppDelegateapplicationDidFinishLaunchingapplicationDidBecomeActiveapplicationWillTerminateuserNotificationCenteruserNotificationCenterapplicationapplicationapplicationapplicationShouldTerminateAfterLastWindowClosedapplicationShouldTerminateUnsavedChangesresolveresolveBufferRestoreStatesavesaverestoreOrgstarAppOrgMenuItemsgroupitemManualViewMenuToggleseditorToggleMarkupToggleFindMenuitemMacroMenuitemAgendaMenuItemSettingsVieweditConfigchooseConfigFolderuseConfigFolderkeyedchoiceschosensettingsFooter
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 Button("Share Subtree…") { commands.run("app.share-subtree") }
545 .disabled(!session.isOrg)
546 Menu("Publish") {
547 ForEach(EditorCommands.all.filter { $0.id.hasPrefix("app.publish") }, id: \.id) { command in
548 Button(command.localizedTitle) { commands.run(command.id) }
549 }
550 }
551 Divider()
552 Button("Revert to File on Disk") { commands.run("app.revert") }
553 .disabled(session.path == nil)
554 Button("Resolve Sync Conflicts…") { commands.run("app.sync-conflicts") }
555 .disabled(session.path == nil)
556 Button("History…") { commands.run("app.recovery") }
557 .disabled(session.path == nil)
558 Button("Lint File") { commands.run("app.lint") }
559 .disabled(!FileLint.applies(to: session.path))
560 }
561 CommandGroup(replacing: .saveItem) {
562 Button("Close Buffer") {
563 // ⌘W closes the buffer in the main window, and other windows themselves.
564 if let key = NSApp.keyWindow, key.identifier?.rawValue.contains("main") != true {
565 key.performClose(nil)
566 } else {
567 commands.run("app.buffer.kill")
568 }
569 }
570 .keyboardShortcut("w")
571 Button("Close Window") { NSApp.keyWindow?.performClose(nil) }
572 .keyboardShortcut("w", modifiers: [.command, .shift])
573 Divider()
574 Button("Save") {
575 if !session.save(), session.conflict != nil { commands.showingConflict = true }
576 }
577 .keyboardShortcut("s")
578 .disabled(session.path == nil || session.isReadOnly)
579 Button("Save All") { commands.run("app.save-all") }
580 .keyboardShortcut("s", modifiers: [.command, .option])
581 .disabled(session.dirtyPaths.isEmpty)
582 }
583 CommandGroup(after: .sidebar) {
584 Button("Split Pane Below") { commands.run("app.split-below") }
585 .keyboardShortcut("2", modifiers: [.command, .control])
586 Button("Split Pane Right") { commands.run("app.split-right") }
587 .keyboardShortcut("3", modifiers: [.command, .control])
588 Button("Close Pane") { commands.run("app.pane-close") }
589 .keyboardShortcut("0", modifiers: [.command, .control])
590 Button("Close Other Panes") { commands.run("app.pane-only") }
591 .keyboardShortcut("1", modifiers: [.command, .control])
592 Button("Next Pane") { commands.run("app.pane-next") }
593 .keyboardShortcut("`", modifiers: [.command, .option])
594 Divider()
595 ViewMenuToggles(commands: commands)
596 Divider()
597 Button("Messages") { commands.run("app.messages") }
598 }
599 CommandGroup(after: .pasteboard) {
600 Divider()
601 FindMenu(commands: commands)
602 MacroMenu(commands: commands)
603 }
604 CommandGroup(after: .textEditing) {
605 Button("Cancel Running Task") { commands.run("app.babel.cancel") }
606 .keyboardShortcut(".")
607 .disabled(!session.isRunningBabel && commands.emacsTask == nil)
608 Button("Search Notes") { commands.focusSearch = true }
609 .keyboardShortcut("f", modifiers: [.command, .shift])
610 }
611 CommandGroup(before: .windowList) {
612 AgendaMenuItem()
613 Divider()
614 Button("Switch to Buffer…") { commands.run("app.buffer.switch") }
615 Button("Next Buffer") { commands.run("app.buffer.next") }
616 .keyboardShortcut("]", modifiers: [.command, .shift])
617 Button("Previous Buffer") { commands.run("app.buffer.previous") }
618 .keyboardShortcut("[", modifiers: [.command, .shift])
619 Divider()
620 }
621 CommandGroup(after: .newItem) {
622 Button("Capture…") { commands.run("app.capture") }
623 .keyboardShortcut("n", modifiers: [.command, .shift])
624 Button("New File from Template…") { commands.run("app.new-file-from-template") }
625 Button("New Window") { commands.run("app.window-new") }
626 .keyboardShortcut("n", modifiers: [.command, .option])
627 }
628 }
629 .commands {
630 CommandMenu("Org") {
631 ClockMenu(commands: commands, clock: clock)
632 Divider()
633 OrgMenuItems(commands: commands)
634 }
635 }
636 .commands {
637 CommandGroup(after: .appSettings) {
638 Button("Edit Config File") { commands.jump(path: UserConfig.configFile.path, offset: 0) }
639 .keyboardShortcut(",", modifiers: [.command, .option])
640 }
641 #if !APPSTORE
642 CommandGroup(after: .appInfo) {
643 CheckForUpdatesItem(updates: delegate.updates)
644 }
645 #endif
646 CommandGroup(replacing: .help) {
647 Button("orgstar Manual") { NSWorkspace.shared.open(Manual.home) }
648 Button("Keys") { NSWorkspace.shared.open(Manual.keys) }
649 Divider()
650 Button("What's New in orgstar") { commands.whatsNew = WhatsNew.releases.first }
651 .disabled(!commands.mainWindowOpen)
652 }
653 }
654 Settings {
655 #if APPSTORE
656 SettingsView(commands: commands, workspace: try? workspace.get())
657 #else
658 SettingsView(commands: commands, workspace: try? workspace.get(), updates: delegate.updates)
659 #endif
660 }
661 }
662}
663
664/// The Org menu: every org command and the app's commands for entries and notes, in submenus by
665/// subject, with the keys that run them in the current keymap.
666struct OrgMenuItems: View {
667 let commands: AppCommands
668
669 /// Submenus and the command id prefixes they hold, in menu order. A command goes in the
670 /// first submenu with a prefix it starts with.
671 static let groups: [(title: LocalizedStringKey, prefixes: [String])] = [
672 ("Visibility", ["org.cycle", "org.fold.", "org.narrow.", "org.widen", "org.sparse-tree", "org.toggle-inline-images", "org.latex-preview"]),
673 ("Headings", ["org.heading.", "org.subtree.", "org.element.", "org.goto", "org.sort", "org.archive.", "app.refile", "app.archive"]),
674 ("TODO and Tags", ["org.todo.", "org.priority.", "org.tags.", "org.effort.", "app.rename-"]),
675 ("Properties and Columns", ["org.property.", "org.columns", "org.drawer."]),
676 ("Dates and Timers", ["org.schedule", "org.deadline", "org.timestamp.", "org.timer."]),
677 ("Lists", ["org.item.", "org.checkbox."]),
678 ("Tables", ["org.table", "app.table-", "app.plot"]),
679 ("Links and Footnotes", ["org.link.", "org.id.", "org.footnote."]),
680 ("Blocks", ["org.babel.", "org.structure-template", "org.edit-special", "org.dblock.", "org.clock.report", "org.denote."]),
681 ("Text", ["org.emphasize", "org.fill-"]),
682 ("Attachments", ["app.attach."]),
683 ("Notes", ["app.dailies.", "app.node."]),
684 ("Encryption", ["app.crypt."]),
685 ]
686
687 private static func group(of id: String) -> Int? {
688 groups.firstIndex { $0.prefixes.contains { id.hasPrefix($0) } }
689 }
690
691 private static let shown = EditorCommands.all.filter { ($0.id.hasPrefix("org.") || group(of: $0.id) != nil) && !hiddenCommandIDs.contains($0.id) }
692
693 var body: some View {
694 // Commands that fit no subject, such as Act at Point, come first.
695 ForEach(Self.shown.filter { Self.group(of: $0.id) == nil }, id: \.id) { item($0) }
696 Divider()
697 ForEach(Self.groups.indices, id: \.self) { index in
698 Menu(Self.groups[index].title) {
699 ForEach(Self.shown.filter { Self.group(of: $0.id) == index }, id: \.id) { item($0) }
700 }
701 }
702 }
703
704 private func item(_ command: EditorCommand) -> some View {
705 Button {
706 if command.id.hasPrefix("org.") { commands.editor?.run(command.id) } else { commands.run(command.id) }
707 } label: {
708 Text(command.localizedTitle)
709 if let keys = commands.keyLabel(for: command.id) { Text(keys) }
710 }
711 .disabled(command.id.hasPrefix("org.") && commands.editor == nil)
712 }
713}
714
715/// The user manual, as `scripts/publish-docs.sh` publishes it.
716enum Manual {
717 static let home = URL(string: "https://files.krz.sh/orgstar/")!
718 /// The key reference, with every preset's keys.
719 static let keys = URL(string: "https://files.krz.sh/orgstar/guide/03-keys.html#key-reference")!
720}
721
722/// View ▸ the panes and the focused editor's modes, checked while on.
723struct ViewMenuToggles: View {
724 let commands: AppCommands
725 @AppStorage("backlinksShown") private var backlinksShown = true
726 @AppStorage("inspectorShown") private var inspectorShown = false
727
728 var body: some View {
729 let outline = commands.outlineShown
730 let editor = commands.editor
731 // A key that switches an editor mode shows a message, so the checks follow it.
732 let _ = commands.message
733 Toggle("Show Outline", isOn: Binding(get: { outline }, set: { _ in commands.run("app.toggle-outline") }))
734 .keyboardShortcut("o", modifiers: [.command, .option])
735 Toggle("Show Backlinks", isOn: $backlinksShown)
736 Toggle("Show Inspector", isOn: $inspectorShown)
737 .keyboardShortcut("i", modifiers: [.command, .option])
738 MarkupToggle()
739 editorToggle("Truncate Long Lines", "editor.toggle-truncate-lines", editor?.truncatesLines)
740 editorToggle("Auto Fill", "editor.toggle-auto-fill", editor?.autoFills)
741 editorToggle("Check Spelling While Typing", "editor.toggle-spell-check", editor?.spellChecking)
742 }
743
744 private func editorToggle(_ title: LocalizedStringKey, _ id: String, _ on: Bool?) -> some View {
745 Toggle(title, isOn: Binding(get: { on ?? false }, set: { _ in commands.editor?.run(id) }))
746 .disabled(on == nil)
747 }
748}
749
750/// View ▸ Show Markup (link brackets and targets, emphasis markers) and Show Line Numbers.
751struct MarkupToggle: View {
752 @AppStorage("showTabBar") private var showTabBar = false
753 @AppStorage("showMarkup") private var showMarkup = false
754 @AppStorage("showLineNumbers") private var showLineNumbers = false
755 @AppStorage("lineNumbersType") private var lineNumbersType = "t"
756
757 var body: some View {
758 Toggle("Show Markup", isOn: $showMarkup)
759 .keyboardShortcut("m", modifiers: [.command, .shift])
760 Toggle("Show Line Numbers", isOn: $showLineNumbers)
761 .keyboardShortcut("l", modifiers: [.command, .shift])
762 Picker("Line Numbers", selection: $lineNumbersType) {
763 Text("Absolute").tag("t")
764 Text("Relative").tag("relative")
765 Text("Visual").tag("visual")
766 }
767 Toggle("Show Tab Bar", isOn: $showTabBar)
768 }
769}
770
771/// Edit ▸ Find: the editor's find bar.
772struct FindMenu: View {
773 let commands: AppCommands
774
775 var body: some View {
776 Menu("Find") {
777 item("Find…", "edit.find", "f")
778 item("Find and Replace…", "edit.replace", "f", [.command, .option])
779 item("Find Next", "edit.find-next", "g")
780 item("Find Previous", "edit.find-previous", "g", [.command, .shift])
781 item("Use Selection for Find", "edit.use-selection-for-find", "e")
782 Divider()
783 Button("Replace in Files…") { commands.run("app.replace-in-files") }
784 .keyboardShortcut("f", modifiers: [.command, .option, .shift])
785 }
786 }
787
788 private func item(_ title: String, _ id: String, _ key: KeyEquivalent, _ modifiers: EventModifiers = .command) -> some View {
789 Button(title) { commands.editor?.run(id) }
790 .keyboardShortcut(key, modifiers: modifiers)
791 .disabled(commands.editor == nil)
792 }
793}
794
795/// Edit ▸ Macros: keyboard macros, with the keys that run them in the current keymap.
796struct MacroMenu: View {
797 let commands: AppCommands
798
799 var body: some View {
800 Menu("Macros") {
801 item("Start Recording", "macro.start")
802 item("Stop Recording", "macro.end")
803 item("Run Last Macro", "macro.call")
804 Divider()
805 item("Name Last Macro…", "macro.name")
806 item("Run Macro…", "macro.run")
807 }
808 }
809
810 private func item(_ title: LocalizedStringKey, _ id: String) -> some View {
811 Button {
812 commands.editor?.run(id)
813 } label: {
814 Text(title)
815 if let keys = commands.keyLabel(for: id) { Text(keys) }
816 }
817 .disabled(commands.editor == nil)
818 }
819}
820
821/// Window ▸ Agenda.
822struct AgendaMenuItem: View {
823 @Environment(\.openWindow) private var openWindow
824
825 var body: some View {
826 Button("Agenda") { openWindow(id: "agenda") }
827 .keyboardShortcut("a", modifiers: [.command, .shift])
828 Button("Board") { openWindow(id: "board") }
829 .keyboardShortcut("b", modifiers: [.command, .shift])
830 Button("Graph") { if ProAccess.shared.allows(.roam) { openWindow(id: "graph") } }
831 }
832}
833
834struct SettingsView: View {
835 let commands: AppCommands
836 let workspace: WorkspaceModel?
837 #if !APPSTORE
838 let updates: Updates
839 #endif
840 @State private var importing = false
841 #if APPSTORE
842 @State private var configFolder = UserConfig.directoryOverride
843 #endif
844 @Environment(\.openWindow) private var openWindow
845 @AppStorage("saveMode") private var saveMode = SaveMode.automatic
846 @AppStorage("keymap") private var preset = KeymapPreset.emacs
847 @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
848 @AppStorage("tagsColumn") private var tagsColumn = -77
849 @AppStorage("headingAfterSubtree") private var headingAfterSubtree = false
850 @AppStorage("splitLine") private var splitLine = false
851 @AppStorage("alphabeticalLists") private var alphabeticalLists = true
852 @AppStorage("fillColumn") private var fillColumn = 80
853 @AppStorage("hiddenMarkers") private var hiddenMarkers = true
854 @AppStorage("prettyEntities") private var prettyEntities = true
855 @AppStorage("startupTruncated") private var startupTruncated = false
856 @AppStorage("todoKeywords") private var todoKeywords = Preferences.defaultTodoKeywords
857 @AppStorage("logDone") private var logDone = "nil"
858 @AppStorage("logIntoDrawer") private var logIntoDrawer = ""
859 @AppStorage("useSpeedCommands") private var useSpeedCommands = false
860 @AppStorage("spellCheck") private var spellCheck = false
861 @AppStorage("completionAuto") private var completionAuto = "preset"
862 @AppStorage("completionAutoDelay") private var completionAutoDelay = 400
863 @AppStorage("completionAutoPrefix") private var completionAutoPrefix = 2
864 @AppStorage("completionStyle") private var completionStyle = "preset"
865 @AppStorage("completionWords") private var completionWords = false
866 @AppStorage("enforceTodoDependencies") private var enforceTodoDependencies = false
867 @AppStorage("enforceTodoCheckboxDependencies") private var enforceTodoCheckboxDependencies = false
868 @AppStorage("agendaSpan") private var agendaSpan = 10
869 @AppStorage("agendaStartOffset") private var agendaStartOffset = 0
870 @AppStorage("agendaSubfolders") private var agendaSubfolders = false
871 @AppStorage("agendaShowAllDates") private var agendaShowAllDates = false
872 @AppStorage("habitsOnlyForToday") private var habitsOnlyForToday = true
873 @AppStorage("agendaDimBlockedTasks") private var agendaDimBlockedTasks = "t"
874 @AppStorage("calendarEvents") private var calendarEvents = false
875 @AppStorage("calendarEventCalendars") private var calendarEventCalendars = ""
876 @State private var calendars: [(id: String, title: String, color: RGBA?)] = []
877 @AppStorage("agendaReminders") private var agendaReminders = false
878 @AppStorage("agendaReminderLists") private var agendaReminderLists = ""
879 @State private var reminderLists: [(id: String, title: String, color: RGBA?)] = []
880 @AppStorage("reminders") private var reminders = true
881 @AppStorage("reminderLead") private var reminderLead = 12
882 @AppStorage("clockIdleTime") private var clockIdleTime = 0
883 @AppStorage("clockHistoryLength") private var clockHistoryLength = 5
884 @AppStorage("globalCapture") private var globalCapture = true
885 @AppStorage("menuBarItem") private var menuBarItem = false
886 @AppStorage("settingsTab") private var tab = "general"
887 @AppStorage("showHiddenFiles") private var showHiddenFiles = true
888 @AppStorage("themeFont") private var themeFont = ""
889 @AppStorage("themeBodyFont") private var themeBodyFont = ""
890 @AppStorage("themeFontSize") private var themeFontSize = 13
891 @AppStorage("themeLineSpacing") private var themeLineSpacing = 2
892 @AppStorage("themeTextWidth") private var themeTextWidth = 0
893 @AppStorage("themeHeadingStep") private var themeHeadingStep = 1
894
895 /// Installed font families that aren't monospaced, for body text.
896 private static let proportionalFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in
897 NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == false
898 }
899
900 /// Installed monospaced font families.
901 private static let monospacedFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in
902 NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == true
903 }
904
905 var body: some View {
906 TabView(selection: $tab) {
907 Tab("General", systemImage: "gearshape", value: "general") { general }
908 Tab("Editing", systemImage: "text.alignleft", value: "editing") { editing }
909 Tab("Appearance", systemImage: "paintpalette", value: "appearance") { appearance }
910 Tab("Agenda", systemImage: "calendar", value: "agenda") { agenda }
911 Tab("Capture", systemImage: "tray.and.arrow.down", value: "capture") { capture }
912 #if !APPSTORE
913 Tab(value: "git") { GitSettingsForm(workspace: workspace) } label: {
914 Label { Text("Git", tableName: "DeveloperID") } icon: { Image(systemName: "arrow.triangle.branch") }
915 }
916 #endif
917 #if APPSTORE
918 Tab("orgstar+", systemImage: "star", value: "pro") { StoreForm() }
919 #else
920 Tab("orgstar+", systemImage: "star", value: "pro") { LicenseForm() }
921 #endif
922 }
923 .frame(width: 600)
924 }
925
926 private func editConfig() {
927 ConfigSync.shared.start()
928 openWindow(id: "main")
929 commands.jump(path: UserConfig.configFile.path, offset: 0)
930 }
931
932 #if APPSTORE
933 /// A folder outside the app's container, such as `~/.config/orgstar` kept with dotfiles.
934 private func chooseConfigFolder() {
935 let panel = NSOpenPanel()
936 panel.canChooseFiles = false
937 panel.canChooseDirectories = true
938 panel.canCreateDirectories = true
939 panel.directoryURL = configFolder ?? ConfigFolder.suggested
940 panel.message = String(localized: "Choose the folder for config.toml and orgstar's other configuration files.", comment: "Choose Configuration Folder panel")
941 guard panel.runModal() == .OK, let url = panel.url else { return }
942 if !ConfigFolder.set(url) {
943 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"),
944 String(localized: "Access lasts until orgstar quits.", comment: "Alert when a folder grant or the configuration folder can't be saved"))
945 }
946 useConfigFolder(url)
947 }
948
949 /// Reads and writes the configuration in `url`, or with nil in the default folder.
950 private func useConfigFolder(_ url: URL?) {
951 if url == nil { ConfigFolder.clear() }
952 UserConfig.directoryOverride = url
953 configFolder = url
954 ConfigSync.shared.move(to: UserConfig.configFile)
955 }
956 #endif
957
958 private var general: some View {
959 Form {
960 Section {
961 LabeledContent("config.toml") {
962 HStack {
963 Button("Edit in orgstar") { editConfig() }
964 Button("Open with Default App") { NSWorkspace.shared.open(UserConfig.configFile) }
965 Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([UserConfig.configFile]) }
966 }
967 }
968 #if APPSTORE
969 LabeledContent("Folder") {
970 HStack {
971 Button("Choose Configuration Folder…") { chooseConfigFolder() }
972 if configFolder != nil { Button("Use Default Folder") { useConfigFolder(nil) } }
973 }
974 }
975 #endif
976 LabeledContent("Emacs") {
977 Button("Import from Emacs…") { importing = true }
978 }
979 } footer: {
980 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.")
981 .settingsFooter()
982 }
983 #if !APPSTORE
984 if updates.canCheck {
985 Section {
986 Toggle(isOn: Binding(get: { updates.automatically }, set: { updates.automatically = $0 })) { Text("Check for updates automatically", tableName: "DeveloperID") }
987 } footer: {
988 Text("Once a day, from the app's own feed. orgstar ▸ Check for Updates… checks now.", tableName: "DeveloperID")
989 .settingsFooter()
990 }
991 }
992 #endif
993 Section {
994 Picker("Save files", selection: $saveMode) {
995 Text("Automatically, when typing stops").tag(SaveMode.automatic)
996 Text("Only with File ▸ Save (⌘S)").tag(SaveMode.explicit)
997 }
998 .pickerStyle(.radioGroup)
999 }
1000 Section {
1001 Picker("Keys", selection: $preset) {
1002 ForEach(KeymapPreset.allCases, id: \.self) { Text($0.title).tag($0) }
1003 }
1004 Toggle("Show hidden files and folders", isOn: $showHiddenFiles)
1005 Toggle("Keep orgstar in the menu bar", isOn: $menuBarItem)
1006 .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.")
1007 Picker("Option as Meta", selection: $optionAsMeta) {
1008 Text("Left Option").tag(OptionAsMeta.left.rawValue)
1009 Text("Right Option").tag(OptionAsMeta.right.rawValue)
1010 Text("Both").tag(OptionAsMeta([.left, .right]).rawValue)
1011 Text("Neither").tag(0)
1012 }
1013 } footer: {
1014 Text("Your own bindings go in \(KeymapLoader.userFile.path), on top of the preset.")
1015 .settingsFooter()
1016 }
1017 }
1018 .formStyle(.grouped)
1019 .frame(height: 330)
1020 .sheet(isPresented: $importing) { EmacsImportView(workspace: workspace) }
1021 }
1022
1023 private var editing: some View {
1024 Form {
1025 Section {
1026 Picker("Tags", selection: $tagsColumn) {
1027 Text("Aligned to end at column 77").tag(-77)
1028 Text("One space after the title").tag(0)
1029 }
1030 .help(Text(verbatim: "org-tags-column"))
1031 Toggle(isOn: $headingAfterSubtree) { keyed("New headings go after the subtree", "org.heading.insert") }
1032 .help(Text(verbatim: "org-insert-heading-respect-content"))
1033 Toggle(isOn: $splitLine) { keyed("New headings and items split the line at the caret", "org.heading.insert") }
1034 .help(Text(verbatim: "org-M-RET-may-split-line"))
1035 Toggle("Lists can use letters (a. b. c.)", isOn: $alphabeticalLists)
1036 .help(Text(verbatim: "org-list-allow-alphabetical"))
1037 Stepper(value: $fillColumn, in: 40...200) { keyed("Fill Paragraph wraps lines at column \(fillColumn)", "org.fill-paragraph") }
1038 .help(Text(verbatim: "fill-column"))
1039 }
1040 Section {
1041 Toggle("Long lines run off the edge instead of wrapping", isOn: $startupTruncated)
1042 .help(Text(verbatim: "org-startup-truncated"))
1043 } footer: {
1044 Text("Applies to files as they open. View ▸ Truncate Long Lines switches the current file.")
1045 .settingsFooter()
1046 }
1047 Section {
1048 Toggle("Emacs hides emphasis markers", isOn: $hiddenMarkers)
1049 .help(Text(verbatim: "org-hide-emphasis-markers"))
1050 Toggle("Emacs shows entities as characters", isOn: $prettyEntities)
1051 .help(Text(verbatim: "org-pretty-entities"))
1052 } footer: {
1053 Text("Tags, tables and Fill Paragraph measure text as your Emacs displays it, so both write the same file.")
1054 .settingsFooter()
1055 }
1056 Section {
1057 TextField("Default TODO keywords", text: $todoKeywords, axis: .vertical)
1058 } footer: {
1059 Text("For files without #+TODO, in #+TODO syntax, one sequence per line. Takes effect when orgstar restarts.")
1060 .settingsFooter()
1061 }
1062 Section {
1063 Toggle("Entries can't be done before their TODO children", isOn: $enforceTodoDependencies)
1064 .help(Text(verbatim: "org-enforce-todo-dependencies"))
1065 Toggle("Entries can't be done with unchecked boxes", isOn: $enforceTodoCheckboxDependencies)
1066 .help(Text(verbatim: "org-enforce-todo-checkbox-dependencies"))
1067 } footer: {
1068 Text("Under a parent with the ORDERED property (Org ▸ Properties and Columns ▸ Toggle ORDERED Property), TODO children are also done in order.")
1069 .settingsFooter()
1070 }
1071 Section {
1072 Picker("When an entry is done", selection: $logDone) {
1073 Text("Record nothing").tag("nil")
1074 Text("Record the time, as CLOSED").tag("time")
1075 Text("Record the time and ask for a note").tag("note")
1076 }
1077 .help(Text(verbatim: "org-log-done"))
1078 Toggle("State notes go in a LOGBOOK drawer", isOn: logIntoDrawerOn)
1079 .help(Text(verbatim: "org-log-into-drawer"))
1080 } footer: {
1081 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.")
1082 .settingsFooter()
1083 }
1084 Section {
1085 Toggle("Speed keys: single letters at the start of a heading line run commands", isOn: $useSpeedCommands)
1086 .help(Text(verbatim: "org-use-speed-commands"))
1087 Toggle("Check spelling while typing", isOn: $spellCheck)
1088 .help(Text(verbatim: "spell-check"))
1089 } footer: {
1090 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.")
1091 .settingsFooter()
1092 }
1093 Section {
1094 Picker("Completion list opens", selection: $completionAuto) {
1095 Text("As the keys do (by itself with Doom)").tag("preset")
1096 Text("By itself as you type").tag("on")
1097 Text("Only with a key").tag("off")
1098 }
1099 .help(Text(verbatim: "completion-auto"))
1100 Stepper("After a pause of \(completionAutoDelay) ms", value: $completionAutoDelay, in: 0...2000, step: 50)
1101 .help(Text(verbatim: "completion-auto-delay"))
1102 Stepper("Once \(completionAutoPrefix) characters are typed", value: $completionAutoPrefix, in: 1...10)
1103 .help(Text(verbatim: "completion-auto-prefix"))
1104 Picker("Candidates", selection: $completionStyle) {
1105 Text("As the keys do (letters in order with Doom)").tag("preset")
1106 Text("Start with what's typed").tag("prefix")
1107 Text("Have its letters in order, best first").tag("fuzzy")
1108 }
1109 .help(Text(verbatim: "completion-style"))
1110 Toggle("The list offers words from open files and folders", isOn: $completionWords)
1111 .help(Text(verbatim: "completion-words"))
1112 } header: {
1113 Text("Completion")
1114 } footer: {
1115 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.")
1116 .settingsFooter()
1117 }
1118 }
1119 .formStyle(.grouped)
1120 .frame(height: 860)
1121 }
1122
1123 /// `label`, then the keys that run `command` in the current preset, if any.
1124 private func keyed(_ label: LocalizedStringKey, _ command: String) -> some View {
1125 HStack(spacing: 6) {
1126 Text(label)
1127 if let keys = commands.keyLabel(for: command) {
1128 Text(verbatim: keys).font(.system(.body, design: .monospaced)).foregroundStyle(.secondary)
1129 }
1130 }
1131 }
1132
1133 /// `org-log-into-drawer` as a switch: on is "LOGBOOK" (Emacs's t); a drawer name of its own counts as on.
1134 private var logIntoDrawerOn: Binding<Bool> {
1135 Binding(get: { !logIntoDrawer.isEmpty }, set: { logIntoDrawer = $0 ? "LOGBOOK" : "" })
1136 }
1137
1138 private var appearance: some View {
1139 Form {
1140 ThemePickerSection()
1141 AppIconSection()
1142 Section {
1143 Picker("Font", selection: $themeFont) {
1144 Text("System monospaced").tag("")
1145 Divider()
1146 ForEach(Self.monospacedFamilies, id: \.self) { Text($0).tag($0) }
1147 if !themeFont.isEmpty, !Self.monospacedFamilies.contains(themeFont) { Text(themeFont).tag(themeFont) }
1148 }
1149 Picker("Body font", selection: $themeBodyFont) {
1150 Text("Same as Font").tag("")
1151 Text("System").tag("system")
1152 Divider()
1153 ForEach(Self.proportionalFamilies, id: \.self) { Text($0).tag($0) }
1154 if !["", "system"].contains(themeBodyFont), !Self.proportionalFamilies.contains(themeBodyFont) { Text(themeBodyFont).tag(themeBodyFont) }
1155 }
1156 Stepper("Size: \(themeFontSize) pt", value: $themeFontSize, in: 8...36)
1157 Stepper("Line spacing: \(themeLineSpacing) pt", value: $themeLineSpacing, in: 0...16)
1158 Picker("Text width", selection: $themeTextWidth) {
1159 Text("Whole editor").tag(0)
1160 ForEach([60, 70, 80, 90, 100, 120], id: \.self) { Text("\($0) columns").tag($0) }
1161 if ![0, 60, 70, 80, 90, 100, 120].contains(themeTextWidth) { Text("\(themeTextWidth) columns").tag(themeTextWidth) }
1162 }
1163 Stepper("Headings grow by \(themeHeadingStep) pt a level", value: $themeHeadingStep, in: 0...8)
1164 } footer: {
1165 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.")
1166 .settingsFooter()
1167 }
1168 Section {
1169 LabeledContent("Colors") {
1170 HStack {
1171 Button("Edit in config.toml") { editConfig() }
1172 Button("Show Default Theme") {
1173 openWindow(id: "main")
1174 commands.jump(path: UserConfig.directory.appendingPathComponent("default-theme.toml").path, offset: 0)
1175 }
1176 }
1177 }
1178 } footer: {
1179 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.")
1180 .settingsFooter()
1181 }
1182 }
1183 .formStyle(.grouped)
1184 .frame(height: 620)
1185 }
1186
1187 private var agenda: some View {
1188 Form {
1189 Section {
1190 Stepper("Agenda shows \(agendaSpan) days", value: $agendaSpan, in: 1...366)
1191 Stepper(agendaStartOffset == 0 ? "Agenda starts today" : "Agenda starts \(-agendaStartOffset) days before today", value: $agendaStartOffset, in: -14...0)
1192 Toggle("Include files in subfolders", isOn: $agendaSubfolders)
1193 Toggle("Show days without entries", isOn: $agendaShowAllDates)
1194 Toggle("Habits only today", isOn: $habitsOnlyForToday)
1195 Picker("Blocked entries", selection: $agendaDimBlockedTasks) {
1196 Text("Dimmed").tag("t")
1197 Text("Hidden").tag("invisible")
1198 Text("Shown as usual").tag("nil")
1199 }
1200 }
1201 Section {
1202 Toggle("Show events from Calendar", isOn: $calendarEvents)
1203 .disabled(!ProAccess.shared.isUnlocked && !calendarEvents)
1204 .help(ProAccess.shared.isUnlocked ? "" : "Needs orgstar+")
1205 if calendarEvents {
1206 choices(calendars, empty: CalendarEvents.isAuthorized ? "No calendars." : "Allow orgstar to read your calendars in System Settings ▸ Privacy & Security ▸ Calendars.", setting: $calendarEventCalendars)
1207 }
1208 } footer: {
1209 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.")
1210 .settingsFooter()
1211 }
1212 .task(id: calendarEvents) {
1213 let allowed = calendarEvents ? await CalendarAccess.events.requestAccess() : false
1214 calendars = allowed ? CalendarAccess.events.calendars() : []
1215 }
1216 Section {
1217 Toggle("Show reminders from Reminders", isOn: $agendaReminders)
1218 .disabled(!ProAccess.shared.isUnlocked && !agendaReminders)
1219 .help(ProAccess.shared.isUnlocked ? "" : "Needs orgstar+")
1220 if agendaReminders {
1221 choices(reminderLists, empty: ReminderLists.isAuthorized ? "No lists." : "Allow orgstar to read your reminders in System Settings ▸ Privacy & Security ▸ Reminders.", setting: $agendaReminderLists)
1222 }
1223 } footer: {
1224 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.")
1225 .settingsFooter()
1226 }
1227 .task(id: agendaReminders) {
1228 let allowed = agendaReminders ? await CalendarAccess.reminders.requestAccess() : false
1229 reminderLists = allowed ? CalendarAccess.reminders.lists() : []
1230 }
1231 Section {
1232 Toggle("Notify before timed agenda entries", isOn: $reminders)
1233 Stepper("\(reminderLead) minutes before", value: $reminderLead, in: 0...120)
1234 .disabled(!reminders)
1235 } footer: {
1236 Text("An entry's APPT_WARNTIME property overrides the lead time.")
1237 .settingsFooter()
1238 }
1239 Section {
1240 Toggle("Ask what to do with idle time while clocked in", isOn: Binding {
1241 clockIdleTime > 0
1242 } set: { on in
1243 clockIdleTime = on ? 15 : 0
1244 })
1245 Stepper("After \(max(clockIdleTime, 1)) minutes without keyboard or mouse input", value: $clockIdleTime, in: 1...240)
1246 .disabled(clockIdleTime == 0)
1247 Stepper("Remember \(clockHistoryLength) recently clocked entries", value: $clockHistoryLength, in: 1...35)
1248 } footer: {
1249 Text("org-clock-idle-time and org-clock-history-length. Org ▸ Clock lists the recent entries.")
1250 .settingsFooter()
1251 }
1252 }
1253 .formStyle(.grouped)
1254 .frame(height: 560)
1255 }
1256
1257 /// A toggle per calendar or reminder list, with its color; `empty` when there are none.
1258 @ViewBuilder
1259 private func choices(_ calendars: [(id: String, title: String, color: RGBA?)], empty: LocalizedStringKey, setting: Binding<String>) -> some View {
1260 if calendars.isEmpty {
1261 Text(empty)
1262 .foregroundStyle(.secondary)
1263 }
1264 ForEach(calendars, id: \.id) { calendar in
1265 Toggle(isOn: chosen(calendar, among: calendars, setting: setting)) {
1266 HStack(spacing: 6) {
1267 Circle()
1268 .fill(calendar.color.map { Color(.sRGB, red: $0.red, green: $0.green, blue: $0.blue, opacity: $0.alpha) } ?? .secondary)
1269 .frame(width: 8, height: 8)
1270 Text(calendar.title)
1271 }
1272 }
1273 }
1274 }
1275
1276 /// `calendar-event-calendars` and `agenda-reminder-lists`: empty for every calendar or
1277 /// list, else the titles checked.
1278 private func chosen(
1279 _ calendar: (id: String, title: String, color: RGBA?), among calendars: [(id: String, title: String, color: RGBA?)], setting: Binding<String>
1280 ) -> Binding<Bool> {
1281 let chosen = setting.wrappedValue.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
1282 return Binding {
1283 CalendarEvents.chooses(id: calendar.id, title: calendar.title, chosen: chosen)
1284 } set: { on in
1285 var titles = calendars.map(\.title).filter { title in
1286 chosen.isEmpty || chosen.contains(title) || chosen.contains(calendars.first { $0.title == title }?.id ?? "")
1287 }
1288 titles.removeAll { $0 == calendar.title }
1289 if on { titles.append(calendar.title) }
1290 // An empty list means every calendar; turning events off hides them all.
1291 guard !titles.isEmpty else { return }
1292 setting.wrappedValue = Set(titles) == Set(calendars.map(\.title)) ? "" : titles.joined(separator: ", ")
1293 }
1294 }
1295
1296 private var capture: some View {
1297 Form {
1298 Section {
1299 Toggle("⌃⌥Space opens Capture from any app", isOn: $globalCapture)
1300 } footer: {
1301 Text("Templates go in \(CaptureTemplates.userFile.path).")
1302 .settingsFooter()
1303 }
1304 }
1305 .formStyle(.grouped)
1306 .frame(height: 160)
1307 }
1308}
1309
1310extension Text {
1311 func settingsFooter() -> some View {
1312 font(.caption)
1313 .foregroundStyle(.secondary)
1314 .textSelection(.enabled)
1315 .frame(maxWidth: .infinity, alignment: .leading)
1316 }
1317}