Sources/Orgstar/OrgstarApp.swift
1365 lines · 66648 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, let path = session.path else { return true }
328 if session.saveMode == .automatic { return save(session, path) }
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 save(session, path)
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 { save(session, $0) }.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 { save(session, $0) }.allSatisfy { $0 }
358 case .alertSecondButtonReturn: return true
359 default: return false
360 }
361 }
362
363 /// Saves `path`. One held for its passphrase asks for it, or whether to leave without saving.
364 static func save(_ session: DocumentSession, _ path: String) -> Bool {
365 if session.save(path) { return true }
366 guard let hold = session.held[path] else { return false }
367 let name = (path as NSString).lastPathComponent
368 // A new passphrase is typed twice; one that must open what's encrypted already, once.
369 let twice = hold == .file || OrgCrypt.firstMessage(session.document(of: path)?.text ?? "") == nil
370 let fields = (twice ? [String(localized: "Passphrase"), String(localized: "Repeat passphrase")] : [String(localized: "Passphrase")]).map { placeholder in
371 let field = NSSecureTextField(frame: NSRect(x: 0, y: 0, width: 260, height: 22))
372 field.placeholderString = placeholder
373 return field
374 }
375 let stack = NSStackView(views: fields)
376 stack.orientation = .vertical
377 stack.spacing = 6
378 stack.frame = NSRect(x: 0, y: 0, width: 260, height: CGFloat(fields.count) * 28)
379 var problem: String?
380 while true {
381 let alert = NSAlert()
382 alert.messageText = String(localized: "Changes to \(name) aren't saved")
383 alert.informativeText = (problem.map { $0 + "\n\n" } ?? "") + hold.notice(for: path) + " "
384 + String(localized: "Enter the passphrase to encrypt and save them, or leave without saving.")
385 alert.accessoryView = stack
386 alert.addButton(withTitle: String(localized: "Encrypt and Save"))
387 alert.addButton(withTitle: String(localized: "Don't Save"))
388 alert.addButton(withTitle: String(localized: "Cancel"))
389 alert.window.initialFirstResponder = fields[0]
390 switch alert.runModal() {
391 case .alertFirstButtonReturn:
392 let passphrase = fields[0].stringValue
393 if passphrase.isEmpty {
394 problem = String(localized: "Enter a passphrase.")
395 } else if twice, fields[1].stringValue != passphrase {
396 problem = String(localized: "The passphrases differ")
397 } else if let failure = session.unlock(passphrase, for: path) {
398 problem = failure
399 } else {
400 return !session.dirtyPaths.contains(path)
401 }
402 case .alertSecondButtonReturn: return true
403 default: return false
404 }
405 }
406 }
407}
408
409/// The open buffers, their order and carets, kept for the next launch.
410@MainActor
411enum BufferRestore {
412 private static let key = "openBuffers"
413
414 struct State: Codable {
415 var paths: [String]
416 var current: String?
417 var carets: [String: Int]
418 /// In the Mac App Store build, bookmarks of the files outside every folder, which the
419 /// sandbox would otherwise keep orgstar out of after relaunch.
420 var bookmarks: [String: Data]?
421 }
422
423 /// `bookmarking` says which paths get a bookmark. A path still open keeps the bookmark it
424 /// has when no new one is made.
425 static func save(_ session: DocumentSession, bookmarking: (String) -> Bool = { _ in false }, defaults: UserDefaults = .standard) {
426 var carets: [String: Int] = [:]
427 for path in session.openPaths { carets[path] = session.caret(of: path) }
428 let previous = defaults.data(forKey: key).flatMap { try? JSONDecoder().decode(State.self, from: $0) }?.bookmarks ?? [:]
429 var bookmarks: [String: Data] = [:]
430 for path in session.openPaths {
431 bookmarks[path] = (bookmarking(path) ? SecurityBookmark.make(URL(fileURLWithPath: path)) : nil) ?? previous[path]
432 }
433 let state = State(paths: session.openPaths, current: session.path, carets: carets, bookmarks: bookmarks.isEmpty ? nil : bookmarks)
434 if let data = try? JSONEncoder().encode(state) { defaults.set(data, forKey: key) }
435 }
436
437 #if APPSTORE
438 /// Saves with bookmarks for the files outside `workspace`'s folders and grants.
439 static func save(_ session: DocumentSession, workspace: WorkspaceModel?) {
440 save(session, bookmarking: { workspace?.contains(URL(fileURLWithPath: $0)) != true })
441 }
442 #endif
443
444 /// Opens the buffers that were open, in order, and returns the carets to show them at.
445 static func restore(_ session: DocumentSession, defaults: UserDefaults = .standard) -> [String: Int] {
446 guard let data = defaults.data(forKey: key), var state = try? JSONDecoder().decode(State.self, from: data) else { return [:] }
447 // A bookmarked file comes back with access, at the path it has now.
448 for (path, bookmark) in state.bookmarks ?? [:] {
449 guard let moved = SecurityBookmark.resolve(bookmark)?.url.path, moved != path else { continue }
450 state.paths = state.paths.map { $0 == path ? moved : $0 }
451 if state.current == path { state.current = moved }
452 state.carets[moved] = state.carets.removeValue(forKey: path)
453 }
454 let existing = state.paths.filter { FileManager.default.fileExists(atPath: $0) }
455 for path in existing { session.open(path) }
456 if let current = state.current, existing.contains(current) { session.open(current) }
457 return state.carets
458 }
459}
460
461@main
462struct OrgstarApp: App {
463 @NSApplicationDelegateAdaptor private var delegate: AppDelegate
464 @State private var workspace = Result {
465 try WorkspaceModel(directory: WorkspaceModel.defaultDirectory, settings: .with(todoKeywords: Preferences.orgSettings))
466 }
467 @State private var commands = AppCommands()
468 @State private var clock = ClockModel()
469 @State private var scheduler = SystemReminderCenter.isAvailable ? ReminderScheduler(center: SystemReminderCenter()) : nil
470 @State private var session: DocumentSession = {
471 let session = DocumentSession()
472 session.defaults = Preferences.orgSettings
473 // Before any window: capture and agenda edits can save before the main window opens.
474 session.encryptsTaggedEntries = OrgPreferences.cryptBeforeSave()
475 session.cryptTag = OrgPreferences.cryptTag()
476 return session
477 }()
478
479 init() {
480 PDFExport.mathJaxURL = OrgMathJax.script
481 DiagramBlocks.vizURL = OrgMathJax.viz
482 DiagramBlocks.mermaidURL = OrgMathJax.mermaid
483 #if APPSTORE
484 AgendaSnapshot.useGroupContainer = true
485 EmacsFallback.offered = false
486 _ = FolderGrants.shared
487 ProStore.shared.start()
488 #else
489 DocumentSession.programs = Programs()
490 MacPro.resolve()
491 MacPro.renewInBackground()
492 #endif
493 // `org-sbe` in table formulas runs blocks, so it needs Babel as source blocks do.
494 TableBlocks.allowed = { ProAccess.isUnlockedNow }
495 // Debug builds, and runs with ORGSTAR_PERF set: main-thread stalls in the console.
496 #if DEBUG
497 Perf.watchMainThread()
498 #else
499 if ProcessInfo.processInfo.environment["ORGSTAR_PERF"] != nil { Perf.watchMainThread() }
500 #endif
501 }
502
503 var body: some Scene {
504 Window("orgstar", id: "main") {
505 switch workspace {
506 case .success(let model):
507 ContentView(workspace: model, session: session, commands: commands, scheduler: scheduler, clock: clock)
508 .environment(\.orgTheme, ConfigSync.shared.theme)
509 .tint(ConfigSync.shared.theme.color("accent"))
510 .onAppear {
511 delegate.session = session
512 delegate.commands = commands
513 #if APPSTORE
514 delegate.workspace = model
515 #else
516 GitAutoCommit.shared.roots = { model.rootPaths }
517 GitAutoCommit.shared.report = { commands.show($0) }
518 session.fileWritten = { GitAutoCommit.shared.fileWritten($0) }
519 #endif
520 CaptureIntent.environment = (model, session, clock, commands)
521 }
522 case .failure(let error):
523 ContentUnavailableView("Can't Open the Index", systemImage: "exclamationmark.triangle", description: Text(error.localizedDescription))
524 }
525 }
526 .defaultSize(width: 1280, height: 860)
527 WindowGroup("Editor", id: "editor") {
528 if case .success = workspace {
529 EditorWindowView(session: session, commands: commands)
530 .environment(\.orgTheme, ConfigSync.shared.theme)
531 .tint(ConfigSync.shared.theme.color("accent"))
532 }
533 }
534 .defaultSize(width: 900, height: 700)
535 .commandsRemoved()
536 Window("Agenda", id: "agenda") {
537 if case .success(let model) = workspace {
538 AgendaView(workspace: model, session: session, commands: commands, scheduler: scheduler, clock: clock)
539 .environment(\.orgTheme, ConfigSync.shared.theme)
540 .tint(ConfigSync.shared.theme.color("accent"))
541 }
542 }
543 .defaultSize(width: 760, height: 720)
544 Window("Board", id: "board") {
545 if case .success(let model) = workspace {
546 BoardView(workspace: model, session: session, commands: commands)
547 .environment(\.orgTheme, ConfigSync.shared.theme)
548 .tint(ConfigSync.shared.theme.color("accent"))
549 }
550 }
551 .defaultSize(width: 1100, height: 700)
552 Window("Node Graph", id: "graph") {
553 if case .success(let model) = workspace {
554 RoamGraphWindow(workspace: model, session: session, commands: commands)
555 .tint(ConfigSync.shared.theme.color("accent"))
556 }
557 }
558 .defaultSize(width: 900, height: 700)
559 Window("Clock Report", id: "clock-report") {
560 if case .success(let model) = workspace {
561 ClockReportView(workspace: model, session: session)
562 .environment(\.orgTheme, ConfigSync.shared.theme)
563 .tint(ConfigSync.shared.theme.color("accent"))
564 }
565 }
566 .defaultSize(width: 860, height: 560)
567 Window("Capture", id: "capture") {
568 if case .success(let model) = workspace {
569 CaptureView(workspace: model, session: session, commands: commands, clock: clock)
570 .environment(\.orgTheme, ConfigSync.shared.theme)
571 .tint(ConfigSync.shared.theme.color("accent"))
572 }
573 }
574 .windowResizability(.contentSize)
575 .windowLevel(.floating)
576 .commands {
577 CommandGroup(after: .newItem) {
578 Button("Add Folder…") { commands.showingFolderPicker = true }
579 .keyboardShortcut("o", modifiers: [.command, .shift])
580 Button("Quick Open…") { commands.showingQuickOpen = true }
581 .keyboardShortcut("p")
582 Button("Command Palette…") { commands.showingPalette = true }
583 .keyboardShortcut("p", modifiers: [.command, .shift])
584 }
585 CommandGroup(after: .saveItem) {
586 Menu("Export") {
587 ForEach(EditorCommands.all.filter { $0.id.hasPrefix("app.export.") && !hiddenCommandIDs.contains($0.id) }, id: \.id) { command in
588 Button(command.localizedTitle) { commands.run(command.id) }
589 }
590 }
591 .disabled(session.path == nil)
592 Button("Share Subtree…") { commands.run("app.share-subtree") }
593 .disabled(!session.isOrg)
594 Menu("Publish") {
595 ForEach(EditorCommands.all.filter { $0.id.hasPrefix("app.publish") }, id: \.id) { command in
596 Button(command.localizedTitle) { commands.run(command.id) }
597 }
598 }
599 Divider()
600 Button("Revert to File on Disk") { commands.run("app.revert") }
601 .disabled(session.path == nil)
602 Button("Resolve Sync Conflicts…") { commands.run("app.sync-conflicts") }
603 .disabled(session.path == nil)
604 Button("History…") { commands.run("app.recovery") }
605 .disabled(session.path == nil)
606 Button("Lint File") { commands.run("app.lint") }
607 .disabled(!FileLint.applies(to: session.path))
608 }
609 CommandGroup(replacing: .saveItem) {
610 Button("Close Buffer") {
611 // ⌘W closes the buffer in the main window, and other windows themselves.
612 if let key = NSApp.keyWindow, key.identifier?.rawValue.contains("main") != true {
613 key.performClose(nil)
614 } else {
615 commands.run("app.buffer.kill")
616 }
617 }
618 .keyboardShortcut("w")
619 Button("Close Window") { NSApp.keyWindow?.performClose(nil) }
620 .keyboardShortcut("w", modifiers: [.command, .shift])
621 Divider()
622 Button("Save") {
623 if !session.save(), session.conflict != nil { commands.showingConflict = true }
624 }
625 .keyboardShortcut("s")
626 .disabled(session.path == nil || session.isReadOnly)
627 Button("Save All") { commands.run("app.save-all") }
628 .keyboardShortcut("s", modifiers: [.command, .option])
629 .disabled(session.dirtyPaths.isEmpty)
630 }
631 CommandGroup(after: .sidebar) {
632 Button("Split Pane Below") { commands.run("app.split-below") }
633 .keyboardShortcut("2", modifiers: [.command, .control])
634 Button("Split Pane Right") { commands.run("app.split-right") }
635 .keyboardShortcut("3", modifiers: [.command, .control])
636 Button("Close Pane") { commands.run("app.pane-close") }
637 .keyboardShortcut("0", modifiers: [.command, .control])
638 Button("Close Other Panes") { commands.run("app.pane-only") }
639 .keyboardShortcut("1", modifiers: [.command, .control])
640 Button("Next Pane") { commands.run("app.pane-next") }
641 .keyboardShortcut("`", modifiers: [.command, .option])
642 Divider()
643 ViewMenuToggles(commands: commands)
644 Divider()
645 Button("Messages") { commands.run("app.messages") }
646 }
647 CommandGroup(after: .pasteboard) {
648 Divider()
649 FindMenu(commands: commands)
650 MacroMenu(commands: commands)
651 }
652 CommandGroup(after: .textEditing) {
653 Button("Cancel Running Task") { commands.run("app.babel.cancel") }
654 .keyboardShortcut(".")
655 .disabled(!session.isRunningBabel && commands.emacsTask == nil)
656 Button("Search Notes") { commands.focusSearch = true }
657 .keyboardShortcut("f", modifiers: [.command, .shift])
658 }
659 CommandGroup(before: .windowList) {
660 AgendaMenuItem()
661 Divider()
662 Button("Switch to Buffer…") { commands.run("app.buffer.switch") }
663 Button("Next Buffer") { commands.run("app.buffer.next") }
664 .keyboardShortcut("]", modifiers: [.command, .shift])
665 Button("Previous Buffer") { commands.run("app.buffer.previous") }
666 .keyboardShortcut("[", modifiers: [.command, .shift])
667 Divider()
668 }
669 CommandGroup(after: .newItem) {
670 Button("Capture…") { commands.run("app.capture") }
671 .keyboardShortcut("n", modifiers: [.command, .shift])
672 Button("New File from Template…") { commands.run("app.new-file-from-template") }
673 Button("New Window") { commands.run("app.window-new") }
674 .keyboardShortcut("n", modifiers: [.command, .option])
675 }
676 }
677 .commands {
678 CommandMenu("Org") {
679 ClockMenu(commands: commands, clock: clock)
680 Divider()
681 OrgMenuItems(commands: commands)
682 }
683 }
684 .commands {
685 CommandGroup(after: .appSettings) {
686 Button("Edit Config File") { commands.jump(path: UserConfig.configFile.path, offset: 0) }
687 .keyboardShortcut(",", modifiers: [.command, .option])
688 }
689 #if !APPSTORE
690 CommandGroup(after: .appInfo) {
691 CheckForUpdatesItem(updates: delegate.updates)
692 }
693 #endif
694 CommandGroup(replacing: .help) {
695 Button("orgstar Manual") { NSWorkspace.shared.open(Manual.home) }
696 Button("Keys") { NSWorkspace.shared.open(Manual.keys) }
697 Divider()
698 Button("What's New in orgstar") { commands.whatsNew = WhatsNew.releases.first }
699 .disabled(!commands.mainWindowOpen)
700 }
701 }
702 Settings {
703 #if APPSTORE
704 SettingsView(commands: commands, workspace: try? workspace.get())
705 #else
706 SettingsView(commands: commands, workspace: try? workspace.get(), updates: delegate.updates)
707 #endif
708 }
709 }
710}
711
712/// The Org menu: every org command and the app's commands for entries and notes, in submenus by
713/// subject, with the keys that run them in the current keymap.
714struct OrgMenuItems: View {
715 let commands: AppCommands
716
717 /// Submenus and the command id prefixes they hold, in menu order. A command goes in the
718 /// first submenu with a prefix it starts with.
719 static let groups: [(title: LocalizedStringKey, prefixes: [String])] = [
720 ("Visibility", ["org.cycle", "org.fold.", "org.narrow.", "org.widen", "org.sparse-tree", "org.toggle-inline-images", "org.latex-preview"]),
721 ("Headings", ["org.heading.", "org.subtree.", "org.element.", "org.goto", "org.sort", "org.archive.", "app.refile", "app.archive"]),
722 ("TODO and Tags", ["org.todo.", "org.priority.", "org.tags.", "org.effort.", "app.rename-"]),
723 ("Properties and Columns", ["org.property.", "org.columns", "org.drawer."]),
724 ("Dates and Timers", ["org.schedule", "org.deadline", "org.timestamp.", "org.timer."]),
725 ("Lists", ["org.item.", "org.checkbox."]),
726 ("Tables", ["org.table", "app.table-", "app.plot"]),
727 ("Links and Footnotes", ["org.link.", "org.id.", "org.footnote."]),
728 ("Blocks", ["org.babel.", "org.structure-template", "org.edit-special", "org.dblock.", "org.clock.report", "org.denote."]),
729 ("Text", ["org.emphasize", "org.fill-"]),
730 ("Attachments", ["app.attach."]),
731 ("Notes", ["app.dailies.", "app.node."]),
732 ("Encryption", ["app.crypt."]),
733 ]
734
735 private static func group(of id: String) -> Int? {
736 groups.firstIndex { $0.prefixes.contains { id.hasPrefix($0) } }
737 }
738
739 private static let shown = EditorCommands.all.filter { ($0.id.hasPrefix("org.") || group(of: $0.id) != nil) && !hiddenCommandIDs.contains($0.id) }
740
741 var body: some View {
742 // Commands that fit no subject, such as Act at Point, come first.
743 ForEach(Self.shown.filter { Self.group(of: $0.id) == nil }, id: \.id) { item($0) }
744 Divider()
745 ForEach(Self.groups.indices, id: \.self) { index in
746 Menu(Self.groups[index].title) {
747 ForEach(Self.shown.filter { Self.group(of: $0.id) == index }, id: \.id) { item($0) }
748 }
749 }
750 }
751
752 private func item(_ command: EditorCommand) -> some View {
753 Button {
754 if command.id.hasPrefix("org.") { commands.editor?.run(command.id) } else { commands.run(command.id) }
755 } label: {
756 Text(command.localizedTitle)
757 if let keys = commands.keyLabel(for: command.id) { Text(keys) }
758 }
759 .disabled(command.id.hasPrefix("org.") && commands.editor == nil)
760 }
761}
762
763/// The user manual, as `scripts/publish-docs.sh` publishes it.
764enum Manual {
765 static let home = URL(string: "https://files.krz.sh/orgstar/")!
766 /// The key reference, with every preset's keys.
767 static let keys = URL(string: "https://files.krz.sh/orgstar/guide/03-keys.html#key-reference")!
768}
769
770/// View ▸ the panes and the focused editor's modes, checked while on.
771struct ViewMenuToggles: View {
772 let commands: AppCommands
773 @AppStorage("backlinksShown") private var backlinksShown = true
774 @AppStorage("inspectorShown") private var inspectorShown = false
775
776 var body: some View {
777 let outline = commands.outlineShown
778 let editor = commands.editor
779 // A key that switches an editor mode shows a message, so the checks follow it.
780 let _ = commands.message
781 Toggle("Show Outline", isOn: Binding(get: { outline }, set: { _ in commands.run("app.toggle-outline") }))
782 .keyboardShortcut("o", modifiers: [.command, .option])
783 Toggle("Show Backlinks", isOn: $backlinksShown)
784 Toggle("Show Inspector", isOn: $inspectorShown)
785 .keyboardShortcut("i", modifiers: [.command, .option])
786 MarkupToggle()
787 editorToggle("Truncate Long Lines", "editor.toggle-truncate-lines", editor?.truncatesLines)
788 editorToggle("Auto Fill", "editor.toggle-auto-fill", editor?.autoFills)
789 editorToggle("Check Spelling While Typing", "editor.toggle-spell-check", editor?.spellChecking)
790 }
791
792 private func editorToggle(_ title: LocalizedStringKey, _ id: String, _ on: Bool?) -> some View {
793 Toggle(title, isOn: Binding(get: { on ?? false }, set: { _ in commands.editor?.run(id) }))
794 .disabled(on == nil)
795 }
796}
797
798/// View ▸ Show Markup (link brackets and targets, emphasis markers) and Show Line Numbers.
799struct MarkupToggle: View {
800 @AppStorage("showTabBar") private var showTabBar = false
801 @AppStorage("showMarkup") private var showMarkup = false
802 @AppStorage("showLineNumbers") private var showLineNumbers = false
803 @AppStorage("lineNumbersType") private var lineNumbersType = "t"
804
805 var body: some View {
806 Toggle("Show Markup", isOn: $showMarkup)
807 .keyboardShortcut("m", modifiers: [.command, .shift])
808 Toggle("Show Line Numbers", isOn: $showLineNumbers)
809 .keyboardShortcut("l", modifiers: [.command, .shift])
810 Picker("Line Numbers", selection: $lineNumbersType) {
811 Text("Absolute").tag("t")
812 Text("Relative").tag("relative")
813 Text("Visual").tag("visual")
814 }
815 Toggle("Show Tab Bar", isOn: $showTabBar)
816 }
817}
818
819/// Edit ▸ Find: the editor's find bar.
820struct FindMenu: View {
821 let commands: AppCommands
822
823 var body: some View {
824 Menu("Find") {
825 item("Find…", "edit.find", "f")
826 item("Find and Replace…", "edit.replace", "f", [.command, .option])
827 item("Find Next", "edit.find-next", "g")
828 item("Find Previous", "edit.find-previous", "g", [.command, .shift])
829 item("Use Selection for Find", "edit.use-selection-for-find", "e")
830 Divider()
831 Button("Replace in Files…") { commands.run("app.replace-in-files") }
832 .keyboardShortcut("f", modifiers: [.command, .option, .shift])
833 }
834 }
835
836 private func item(_ title: String, _ id: String, _ key: KeyEquivalent, _ modifiers: EventModifiers = .command) -> some View {
837 Button(title) { commands.editor?.run(id) }
838 .keyboardShortcut(key, modifiers: modifiers)
839 .disabled(commands.editor == nil)
840 }
841}
842
843/// Edit ▸ Macros: keyboard macros, with the keys that run them in the current keymap.
844struct MacroMenu: View {
845 let commands: AppCommands
846
847 var body: some View {
848 Menu("Macros") {
849 item("Start Recording", "macro.start")
850 item("Stop Recording", "macro.end")
851 item("Run Last Macro", "macro.call")
852 Divider()
853 item("Name Last Macro…", "macro.name")
854 item("Run Macro…", "macro.run")
855 }
856 }
857
858 private func item(_ title: LocalizedStringKey, _ id: String) -> some View {
859 Button {
860 commands.editor?.run(id)
861 } label: {
862 Text(title)
863 if let keys = commands.keyLabel(for: id) { Text(keys) }
864 }
865 .disabled(commands.editor == nil)
866 }
867}
868
869/// Window ▸ Agenda.
870struct AgendaMenuItem: View {
871 @Environment(\.openWindow) private var openWindow
872
873 var body: some View {
874 Button("Agenda") { openWindow(id: "agenda") }
875 .keyboardShortcut("a", modifiers: [.command, .shift])
876 Button("Board") { openWindow(id: "board") }
877 .keyboardShortcut("b", modifiers: [.command, .shift])
878 Button("Graph") { if ProAccess.shared.allows(.roam) { openWindow(id: "graph") } }
879 }
880}
881
882struct SettingsView: View {
883 let commands: AppCommands
884 let workspace: WorkspaceModel?
885 #if !APPSTORE
886 let updates: Updates
887 #endif
888 @State private var importing = false
889 #if APPSTORE
890 @State private var configFolder = UserConfig.directoryOverride
891 #endif
892 @Environment(\.openWindow) private var openWindow
893 @AppStorage("saveMode") private var saveMode = SaveMode.automatic
894 @AppStorage("keymap") private var preset = KeymapPreset.emacs
895 @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
896 @AppStorage("tagsColumn") private var tagsColumn = -77
897 @AppStorage("headingAfterSubtree") private var headingAfterSubtree = false
898 @AppStorage("splitLine") private var splitLine = false
899 @AppStorage("alphabeticalLists") private var alphabeticalLists = true
900 @AppStorage("fillColumn") private var fillColumn = 80
901 @AppStorage("hiddenMarkers") private var hiddenMarkers = true
902 @AppStorage("prettyEntities") private var prettyEntities = true
903 @AppStorage("startupTruncated") private var startupTruncated = false
904 @AppStorage("todoKeywords") private var todoKeywords = Preferences.defaultTodoKeywords
905 @AppStorage("logDone") private var logDone = "nil"
906 @AppStorage("logIntoDrawer") private var logIntoDrawer = ""
907 @AppStorage("useSpeedCommands") private var useSpeedCommands = false
908 @AppStorage("spellCheck") private var spellCheck = false
909 @AppStorage("completionAuto") private var completionAuto = "preset"
910 @AppStorage("completionAutoDelay") private var completionAutoDelay = 400
911 @AppStorage("completionAutoPrefix") private var completionAutoPrefix = 2
912 @AppStorage("completionStyle") private var completionStyle = "preset"
913 @AppStorage("completionWords") private var completionWords = false
914 @AppStorage("enforceTodoDependencies") private var enforceTodoDependencies = false
915 @AppStorage("enforceTodoCheckboxDependencies") private var enforceTodoCheckboxDependencies = false
916 @AppStorage("agendaSpan") private var agendaSpan = 10
917 @AppStorage("agendaStartOffset") private var agendaStartOffset = 0
918 @AppStorage("agendaSubfolders") private var agendaSubfolders = false
919 @AppStorage("agendaShowAllDates") private var agendaShowAllDates = false
920 @AppStorage("habitsOnlyForToday") private var habitsOnlyForToday = true
921 @AppStorage("agendaDimBlockedTasks") private var agendaDimBlockedTasks = "t"
922 @AppStorage("calendarEvents") private var calendarEvents = false
923 @AppStorage("calendarEventCalendars") private var calendarEventCalendars = ""
924 @State private var calendars: [(id: String, title: String, color: RGBA?)] = []
925 @AppStorage("agendaReminders") private var agendaReminders = false
926 @AppStorage("agendaReminderLists") private var agendaReminderLists = ""
927 @State private var reminderLists: [(id: String, title: String, color: RGBA?)] = []
928 @AppStorage("reminders") private var reminders = true
929 @AppStorage("reminderLead") private var reminderLead = 12
930 @AppStorage("clockIdleTime") private var clockIdleTime = 0
931 @AppStorage("clockHistoryLength") private var clockHistoryLength = 5
932 @AppStorage("globalCapture") private var globalCapture = true
933 @AppStorage("menuBarItem") private var menuBarItem = false
934 @AppStorage("settingsTab") private var tab = "general"
935 @AppStorage("showHiddenFiles") private var showHiddenFiles = true
936 @AppStorage("themeFont") private var themeFont = ""
937 @AppStorage("themeBodyFont") private var themeBodyFont = ""
938 @AppStorage("themeFontSize") private var themeFontSize = 13
939 @AppStorage("themeLineSpacing") private var themeLineSpacing = 2
940 @AppStorage("themeTextWidth") private var themeTextWidth = 0
941 @AppStorage("themeHeadingStep") private var themeHeadingStep = 1
942
943 /// Installed font families that aren't monospaced, for body text.
944 private static let proportionalFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in
945 NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == false
946 }
947
948 /// Installed monospaced font families.
949 private static let monospacedFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in
950 NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == true
951 }
952
953 var body: some View {
954 TabView(selection: $tab) {
955 Tab("General", systemImage: "gearshape", value: "general") { general }
956 Tab("Editing", systemImage: "text.alignleft", value: "editing") { editing }
957 Tab("Appearance", systemImage: "paintpalette", value: "appearance") { appearance }
958 Tab("Agenda", systemImage: "calendar", value: "agenda") { agenda }
959 Tab("Capture", systemImage: "tray.and.arrow.down", value: "capture") { capture }
960 #if !APPSTORE
961 Tab(value: "git") { GitSettingsForm(workspace: workspace) } label: {
962 Label { Text("Git", tableName: "DeveloperID") } icon: { Image(systemName: "arrow.triangle.branch") }
963 }
964 #endif
965 #if APPSTORE
966 Tab("orgstar+", systemImage: "star", value: "pro") { StoreForm() }
967 #else
968 Tab("orgstar+", systemImage: "star", value: "pro") { LicenseForm() }
969 #endif
970 }
971 .frame(width: 600)
972 }
973
974 private func editConfig() {
975 ConfigSync.shared.start()
976 openWindow(id: "main")
977 commands.jump(path: UserConfig.configFile.path, offset: 0)
978 }
979
980 #if APPSTORE
981 /// A folder outside the app's container, such as `~/.config/orgstar` kept with dotfiles.
982 private func chooseConfigFolder() {
983 let panel = NSOpenPanel()
984 panel.canChooseFiles = false
985 panel.canChooseDirectories = true
986 panel.canCreateDirectories = true
987 panel.directoryURL = configFolder ?? ConfigFolder.suggested
988 panel.message = String(localized: "Choose the folder for config.toml and orgstar's other configuration files.", comment: "Choose Configuration Folder panel")
989 guard panel.runModal() == .OK, let url = panel.url else { return }
990 if !ConfigFolder.set(url) {
991 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"),
992 String(localized: "Access lasts until orgstar quits.", comment: "Alert when a folder grant or the configuration folder can't be saved"))
993 }
994 useConfigFolder(url)
995 }
996
997 /// Reads and writes the configuration in `url`, or with nil in the default folder.
998 private func useConfigFolder(_ url: URL?) {
999 if url == nil { ConfigFolder.clear() }
1000 UserConfig.directoryOverride = url
1001 configFolder = url
1002 ConfigSync.shared.move(to: UserConfig.configFile)
1003 }
1004 #endif
1005
1006 private var general: some View {
1007 Form {
1008 Section {
1009 LabeledContent("config.toml") {
1010 HStack {
1011 Button("Edit in orgstar") { editConfig() }
1012 Button("Open with Default App") { NSWorkspace.shared.open(UserConfig.configFile) }
1013 Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([UserConfig.configFile]) }
1014 }
1015 }
1016 #if APPSTORE
1017 LabeledContent("Folder") {
1018 HStack {
1019 Button("Choose Configuration Folder…") { chooseConfigFolder() }
1020 if configFolder != nil { Button("Use Default Folder") { useConfigFolder(nil) } }
1021 }
1022 }
1023 #endif
1024 LabeledContent("Emacs") {
1025 Button("Import from Emacs…") { importing = true }
1026 }
1027 } footer: {
1028 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.")
1029 .settingsFooter()
1030 }
1031 #if !APPSTORE
1032 if updates.canCheck {
1033 Section {
1034 Toggle(isOn: Binding(get: { updates.automatically }, set: { updates.automatically = $0 })) { Text("Check for updates automatically", tableName: "DeveloperID") }
1035 } footer: {
1036 Text("Once a day, from the app's own feed. orgstar ▸ Check for Updates… checks now.", tableName: "DeveloperID")
1037 .settingsFooter()
1038 }
1039 }
1040 #endif
1041 Section {
1042 Picker("Save files", selection: $saveMode) {
1043 Text("Automatically, when typing stops").tag(SaveMode.automatic)
1044 Text("Only with File ▸ Save (⌘S)").tag(SaveMode.explicit)
1045 }
1046 .pickerStyle(.radioGroup)
1047 }
1048 Section {
1049 Picker("Keys", selection: $preset) {
1050 ForEach(KeymapPreset.allCases, id: \.self) { Text($0.title).tag($0) }
1051 }
1052 Toggle("Show hidden files and folders", isOn: $showHiddenFiles)
1053 Toggle("Keep orgstar in the menu bar", isOn: $menuBarItem)
1054 .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.")
1055 Picker("Option as Meta", selection: $optionAsMeta) {
1056 Text("Left Option").tag(OptionAsMeta.left.rawValue)
1057 Text("Right Option").tag(OptionAsMeta.right.rawValue)
1058 Text("Both").tag(OptionAsMeta([.left, .right]).rawValue)
1059 Text("Neither").tag(0)
1060 }
1061 } footer: {
1062 Text("Your own bindings go in \(KeymapLoader.userFile.path), on top of the preset.")
1063 .settingsFooter()
1064 }
1065 }
1066 .formStyle(.grouped)
1067 .frame(height: 330)
1068 .sheet(isPresented: $importing) { EmacsImportView(workspace: workspace) }
1069 }
1070
1071 private var editing: some View {
1072 Form {
1073 Section {
1074 Picker("Tags", selection: $tagsColumn) {
1075 Text("Aligned to end at column 77").tag(-77)
1076 Text("One space after the title").tag(0)
1077 }
1078 .help(Text(verbatim: "org-tags-column"))
1079 Toggle(isOn: $headingAfterSubtree) { keyed("New headings go after the subtree", "org.heading.insert") }
1080 .help(Text(verbatim: "org-insert-heading-respect-content"))
1081 Toggle(isOn: $splitLine) { keyed("New headings and items split the line at the caret", "org.heading.insert") }
1082 .help(Text(verbatim: "org-M-RET-may-split-line"))
1083 Toggle("Lists can use letters (a. b. c.)", isOn: $alphabeticalLists)
1084 .help(Text(verbatim: "org-list-allow-alphabetical"))
1085 Stepper(value: $fillColumn, in: 40...200) { keyed("Fill Paragraph wraps lines at column \(fillColumn)", "org.fill-paragraph") }
1086 .help(Text(verbatim: "fill-column"))
1087 }
1088 Section {
1089 Toggle("Long lines run off the edge instead of wrapping", isOn: $startupTruncated)
1090 .help(Text(verbatim: "org-startup-truncated"))
1091 } footer: {
1092 Text("Applies to files as they open. View ▸ Truncate Long Lines switches the current file.")
1093 .settingsFooter()
1094 }
1095 Section {
1096 Toggle("Emacs hides emphasis markers", isOn: $hiddenMarkers)
1097 .help(Text(verbatim: "org-hide-emphasis-markers"))
1098 Toggle("Emacs shows entities as characters", isOn: $prettyEntities)
1099 .help(Text(verbatim: "org-pretty-entities"))
1100 } footer: {
1101 Text("Tags, tables and Fill Paragraph measure text as your Emacs displays it, so both write the same file.")
1102 .settingsFooter()
1103 }
1104 Section {
1105 TextField("Default TODO keywords", text: $todoKeywords, axis: .vertical)
1106 } footer: {
1107 Text("For files without #+TODO, in #+TODO syntax, one sequence per line. Takes effect when orgstar restarts.")
1108 .settingsFooter()
1109 }
1110 Section {
1111 Toggle("Entries can't be done before their TODO children", isOn: $enforceTodoDependencies)
1112 .help(Text(verbatim: "org-enforce-todo-dependencies"))
1113 Toggle("Entries can't be done with unchecked boxes", isOn: $enforceTodoCheckboxDependencies)
1114 .help(Text(verbatim: "org-enforce-todo-checkbox-dependencies"))
1115 } footer: {
1116 Text("Under a parent with the ORDERED property (Org ▸ Properties and Columns ▸ Toggle ORDERED Property), TODO children are also done in order.")
1117 .settingsFooter()
1118 }
1119 Section {
1120 Picker("When an entry is done", selection: $logDone) {
1121 Text("Record nothing").tag("nil")
1122 Text("Record the time, as CLOSED").tag("time")
1123 Text("Record the time and ask for a note").tag("note")
1124 }
1125 .help(Text(verbatim: "org-log-done"))
1126 Toggle("State notes go in a LOGBOOK drawer", isOn: logIntoDrawerOn)
1127 .help(Text(verbatim: "org-log-into-drawer"))
1128 } footer: {
1129 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.")
1130 .settingsFooter()
1131 }
1132 Section {
1133 Toggle("Speed keys: single letters at the start of a heading line run commands", isOn: $useSpeedCommands)
1134 .help(Text(verbatim: "org-use-speed-commands"))
1135 Toggle("Check spelling while typing", isOn: $spellCheck)
1136 .help(Text(verbatim: "spell-check"))
1137 } footer: {
1138 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.")
1139 .settingsFooter()
1140 }
1141 Section {
1142 Picker("Completion list opens", selection: $completionAuto) {
1143 Text("As the keys do (by itself with Doom)").tag("preset")
1144 Text("By itself as you type").tag("on")
1145 Text("Only with a key").tag("off")
1146 }
1147 .help(Text(verbatim: "completion-auto"))
1148 Stepper("After a pause of \(completionAutoDelay) ms", value: $completionAutoDelay, in: 0...2000, step: 50)
1149 .help(Text(verbatim: "completion-auto-delay"))
1150 Stepper("Once \(completionAutoPrefix) characters are typed", value: $completionAutoPrefix, in: 1...10)
1151 .help(Text(verbatim: "completion-auto-prefix"))
1152 Picker("Candidates", selection: $completionStyle) {
1153 Text("As the keys do (letters in order with Doom)").tag("preset")
1154 Text("Start with what's typed").tag("prefix")
1155 Text("Have its letters in order, best first").tag("fuzzy")
1156 }
1157 .help(Text(verbatim: "completion-style"))
1158 Toggle("The list offers words from open files and folders", isOn: $completionWords)
1159 .help(Text(verbatim: "completion-words"))
1160 } header: {
1161 Text("Completion")
1162 } footer: {
1163 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.")
1164 .settingsFooter()
1165 }
1166 }
1167 .formStyle(.grouped)
1168 .frame(height: 860)
1169 }
1170
1171 /// `label`, then the keys that run `command` in the current preset, if any.
1172 private func keyed(_ label: LocalizedStringKey, _ command: String) -> some View {
1173 HStack(spacing: 6) {
1174 Text(label)
1175 if let keys = commands.keyLabel(for: command) {
1176 Text(verbatim: keys).font(.system(.body, design: .monospaced)).foregroundStyle(.secondary)
1177 }
1178 }
1179 }
1180
1181 /// `org-log-into-drawer` as a switch: on is "LOGBOOK" (Emacs's t); a drawer name of its own counts as on.
1182 private var logIntoDrawerOn: Binding<Bool> {
1183 Binding(get: { !logIntoDrawer.isEmpty }, set: { logIntoDrawer = $0 ? "LOGBOOK" : "" })
1184 }
1185
1186 private var appearance: some View {
1187 Form {
1188 ThemePickerSection()
1189 AppIconSection()
1190 Section {
1191 Picker("Font", selection: $themeFont) {
1192 Text("System monospaced").tag("")
1193 Divider()
1194 ForEach(Self.monospacedFamilies, id: \.self) { Text($0).tag($0) }
1195 if !themeFont.isEmpty, !Self.monospacedFamilies.contains(themeFont) { Text(themeFont).tag(themeFont) }
1196 }
1197 Picker("Body font", selection: $themeBodyFont) {
1198 Text("Same as Font").tag("")
1199 Text("System").tag("system")
1200 Divider()
1201 ForEach(Self.proportionalFamilies, id: \.self) { Text($0).tag($0) }
1202 if !["", "system"].contains(themeBodyFont), !Self.proportionalFamilies.contains(themeBodyFont) { Text(themeBodyFont).tag(themeBodyFont) }
1203 }
1204 Stepper("Size: \(themeFontSize) pt", value: $themeFontSize, in: 8...36)
1205 Stepper("Line spacing: \(themeLineSpacing) pt", value: $themeLineSpacing, in: 0...16)
1206 Picker("Text width", selection: $themeTextWidth) {
1207 Text("Whole editor").tag(0)
1208 ForEach([60, 70, 80, 90, 100, 120], id: \.self) { Text("\($0) columns").tag($0) }
1209 if ![0, 60, 70, 80, 90, 100, 120].contains(themeTextWidth) { Text("\(themeTextWidth) columns").tag(themeTextWidth) }
1210 }
1211 Stepper("Headings grow by \(themeHeadingStep) pt a level", value: $themeHeadingStep, in: 0...8)
1212 } footer: {
1213 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.")
1214 .settingsFooter()
1215 }
1216 Section {
1217 LabeledContent("Colors") {
1218 HStack {
1219 Button("Edit in config.toml") { editConfig() }
1220 Button("Show Default Theme") {
1221 openWindow(id: "main")
1222 commands.jump(path: UserConfig.directory.appendingPathComponent("default-theme.toml").path, offset: 0)
1223 }
1224 }
1225 }
1226 } footer: {
1227 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.")
1228 .settingsFooter()
1229 }
1230 }
1231 .formStyle(.grouped)
1232 .frame(height: 620)
1233 }
1234
1235 private var agenda: some View {
1236 Form {
1237 Section {
1238 Stepper("Agenda shows \(agendaSpan) days", value: $agendaSpan, in: 1...366)
1239 Stepper(agendaStartOffset == 0 ? "Agenda starts today" : "Agenda starts \(-agendaStartOffset) days before today", value: $agendaStartOffset, in: -14...0)
1240 Toggle("Include files in subfolders", isOn: $agendaSubfolders)
1241 Toggle("Show days without entries", isOn: $agendaShowAllDates)
1242 Toggle("Habits only today", isOn: $habitsOnlyForToday)
1243 Picker("Blocked entries", selection: $agendaDimBlockedTasks) {
1244 Text("Dimmed").tag("t")
1245 Text("Hidden").tag("invisible")
1246 Text("Shown as usual").tag("nil")
1247 }
1248 }
1249 Section {
1250 Toggle("Show events from Calendar", isOn: $calendarEvents)
1251 .disabled(!ProAccess.shared.isUnlocked && !calendarEvents)
1252 .help(ProAccess.shared.isUnlocked ? "" : "Needs orgstar+")
1253 if calendarEvents {
1254 choices(calendars, empty: CalendarEvents.isAuthorized ? "No calendars." : "Allow orgstar to read your calendars in System Settings ▸ Privacy & Security ▸ Calendars.", setting: $calendarEventCalendars)
1255 }
1256 } footer: {
1257 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.")
1258 .settingsFooter()
1259 }
1260 .task(id: calendarEvents) {
1261 let allowed = calendarEvents ? await CalendarAccess.events.requestAccess() : false
1262 calendars = allowed ? CalendarAccess.events.calendars() : []
1263 }
1264 Section {
1265 Toggle("Show reminders from Reminders", isOn: $agendaReminders)
1266 .disabled(!ProAccess.shared.isUnlocked && !agendaReminders)
1267 .help(ProAccess.shared.isUnlocked ? "" : "Needs orgstar+")
1268 if agendaReminders {
1269 choices(reminderLists, empty: ReminderLists.isAuthorized ? "No lists." : "Allow orgstar to read your reminders in System Settings ▸ Privacy & Security ▸ Reminders.", setting: $agendaReminderLists)
1270 }
1271 } footer: {
1272 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.")
1273 .settingsFooter()
1274 }
1275 .task(id: agendaReminders) {
1276 let allowed = agendaReminders ? await CalendarAccess.reminders.requestAccess() : false
1277 reminderLists = allowed ? CalendarAccess.reminders.lists() : []
1278 }
1279 Section {
1280 Toggle("Notify before timed agenda entries", isOn: $reminders)
1281 Stepper("\(reminderLead) minutes before", value: $reminderLead, in: 0...120)
1282 .disabled(!reminders)
1283 } footer: {
1284 Text("An entry's APPT_WARNTIME property overrides the lead time.")
1285 .settingsFooter()
1286 }
1287 Section {
1288 Toggle("Ask what to do with idle time while clocked in", isOn: Binding {
1289 clockIdleTime > 0
1290 } set: { on in
1291 clockIdleTime = on ? 15 : 0
1292 })
1293 Stepper("After \(max(clockIdleTime, 1)) minutes without keyboard or mouse input", value: $clockIdleTime, in: 1...240)
1294 .disabled(clockIdleTime == 0)
1295 Stepper("Remember \(clockHistoryLength) recently clocked entries", value: $clockHistoryLength, in: 1...35)
1296 } footer: {
1297 Text("org-clock-idle-time and org-clock-history-length. Org ▸ Clock lists the recent entries.")
1298 .settingsFooter()
1299 }
1300 }
1301 .formStyle(.grouped)
1302 .frame(height: 560)
1303 }
1304
1305 /// A toggle per calendar or reminder list, with its color; `empty` when there are none.
1306 @ViewBuilder
1307 private func choices(_ calendars: [(id: String, title: String, color: RGBA?)], empty: LocalizedStringKey, setting: Binding<String>) -> some View {
1308 if calendars.isEmpty {
1309 Text(empty)
1310 .foregroundStyle(.secondary)
1311 }
1312 ForEach(calendars, id: \.id) { calendar in
1313 Toggle(isOn: chosen(calendar, among: calendars, setting: setting)) {
1314 HStack(spacing: 6) {
1315 Circle()
1316 .fill(calendar.color.map { Color(.sRGB, red: $0.red, green: $0.green, blue: $0.blue, opacity: $0.alpha) } ?? .secondary)
1317 .frame(width: 8, height: 8)
1318 Text(calendar.title)
1319 }
1320 }
1321 }
1322 }
1323
1324 /// `calendar-event-calendars` and `agenda-reminder-lists`: empty for every calendar or
1325 /// list, else the titles checked.
1326 private func chosen(
1327 _ calendar: (id: String, title: String, color: RGBA?), among calendars: [(id: String, title: String, color: RGBA?)], setting: Binding<String>
1328 ) -> Binding<Bool> {
1329 let chosen = setting.wrappedValue.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
1330 return Binding {
1331 CalendarEvents.chooses(id: calendar.id, title: calendar.title, chosen: chosen)
1332 } set: { on in
1333 var titles = calendars.map(\.title).filter { title in
1334 chosen.isEmpty || chosen.contains(title) || chosen.contains(calendars.first { $0.title == title }?.id ?? "")
1335 }
1336 titles.removeAll { $0 == calendar.title }
1337 if on { titles.append(calendar.title) }
1338 // An empty list means every calendar; turning events off hides them all.
1339 guard !titles.isEmpty else { return }
1340 setting.wrappedValue = Set(titles) == Set(calendars.map(\.title)) ? "" : titles.joined(separator: ", ")
1341 }
1342 }
1343
1344 private var capture: some View {
1345 Form {
1346 Section {
1347 Toggle("⌃⌥Space opens Capture from any app", isOn: $globalCapture)
1348 } footer: {
1349 Text("Templates go in \(CaptureTemplates.userFile.path).")
1350 .settingsFooter()
1351 }
1352 }
1353 .formStyle(.grouped)
1354 .frame(height: 160)
1355 }
1356}
1357
1358extension Text {
1359 func settingsFooter() -> some View {
1360 font(.caption)
1361 .foregroundStyle(.secondary)
1362 .textSelection(.enabled)
1363 .frame(maxWidth: .infinity, alignment: .leading)
1364 }
1365}