Sources/Orgstar/OrgstarApp.swift

b5b0571216b98cb8eeee4c61f6c0576ec13ba6a0
orgstar/Sources/Orgstar/OrgstarApp.swift

618 lines · 26785 bytes

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form