Sources/Orgstar/ContentView.swift
1028 lines · 49964 bytes
23 symbols in this file
1import AppKit
2import OrgApp
3import OrgCore
4import OrgEditorAppKit
5import OrgPresentation
6import OrgWorkspace
7import OrgIndex
8import SwiftUI
9import UniformTypeIdentifiers
10
11struct ContentView: View {
12 let workspace: WorkspaceModel
13 let session: DocumentSession
14 @Bindable var commands: AppCommands
15 let scheduler: ReminderScheduler?
16 let clock: ClockModel
17 @AppStorage("reminders") private var remindersEnabled = true
18 @AppStorage("reminderLead") private var reminderLead = 12
19 @AppStorage("clockIdleTime") private var clockIdleTime = 0
20 @AppStorage("agendaSubfolders") private var agendaSubfolders = false
21 @State private var reminderAgenda: AgendaModel?
22 @State private var trust = TrustStore()
23 @State private var hotKey: GlobalHotKey?
24 @State private var statusItem: ClockStatusItem?
25 @AppStorage("globalCapture") private var globalCapture = true
26 @State private var hour = 0
27 @AppStorage("saveMode") private var saveMode = SaveMode.automatic
28 @AppStorage("keymap") private var preset = KeymapPreset.emacs
29 @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
30 @State private var keymap = KeymapPreset.emacs.keymap
31 @AppStorage("tagsColumn") private var tagsColumn = -77
32 @AppStorage("headingAfterSubtree") private var headingAfterSubtree = true
33 @AppStorage("splitLine") private var splitLine = false
34 @AppStorage("alphabeticalLists") private var alphabeticalLists = true
35 @AppStorage("fillColumn") private var fillColumn = 80
36 @AppStorage("hiddenMarkers") private var hiddenMarkers = true
37 @AppStorage("prettyEntities") private var prettyEntities = true
38 @AppStorage("logDone") private var logDone = "nil"
39 @AppStorage("logIntoDrawer") private var logIntoDrawer = ""
40 @AppStorage("logReschedule") private var logReschedule = "nil"
41 @AppStorage("logRedeadline") private var logRedeadline = "nil"
42 @AppStorage("useSpeedCommands") private var useSpeedCommands = false
43 @AppStorage("startupWithInlineImages") private var startupWithInlineImages = false
44 @AppStorage("startupIndented") private var startupIndented = true
45 @AppStorage("hideLeadingStars") private var hideLeadingStars = false
46 @AppStorage("startupAlignAllTables") private var startupAlignAllTables = false
47 @AppStorage("startupTruncated") private var startupTruncated = false
48 @AppStorage("spellCheck") private var spellCheck = false
49 @AppStorage("electricPair") private var electricPair = true
50 @AppStorage("hideDrawerStartup") private var hideDrawerStartup = true
51 @AppStorage("hideBlockStartup") private var hideBlockStartup = false
52
53 private var options: EditingOptions {
54 Preferences.options(
55 tagsColumn: tagsColumn, headingAfterSubtree: headingAfterSubtree, splitLine: splitLine, alphabeticalLists: alphabeticalLists,
56 fillColumn: fillColumn, hiddenMarkers: hiddenMarkers, prettyEntities: prettyEntities, logDone: logDone, logIntoDrawer: logIntoDrawer,
57 hideDrawerStartup: hideDrawerStartup, hideBlockStartup: hideBlockStartup, logReschedule: logReschedule, logRedeadline: logRedeadline,
58 useSpeedCommands: useSpeedCommands, startupWithInlineImages: startupWithInlineImages,
59 startupIndented: startupIndented, hideLeadingStars: hideLeadingStars, startupAlignAllTables: startupAlignAllTables,
60 startupTruncated: startupTruncated, spellCheck: spellCheck, electricPair: electricPair
61 )
62 }
63 /// A block being edited apart (`org-edit-special`).
64 @State private var blockEdit: BlockEditRequest?
65 /// A sheet a command opened: column view or the export dialog.
66 @State private var panel: Panel?
67
68 @State private var selectedFile: String?
69 /// A file that isn't text, shown as a preview instead of the open document.
70 @State private var previewPath: String?
71 @AppStorage("outlineShown") private var orgOutlineShown = true
72 @AppStorage("outlineWidth") private var outlineWidth = 220.0
73 @AppStorage("backlinksShown") private var backlinksShown = true
74 @AppStorage("inspectorShown") private var inspectorShown = false
75 @AppStorage("showMarkup") private var showMarkup = false
76 @AppStorage("showLineNumbers") private var showLineNumbers = true
77 @AppStorage("showHiddenFiles") private var showHiddenFiles = true
78 @AppStorage("ignoredFolders") private var ignoredFolders = ScanRules.defaultIgnoredFolders.sorted().joined(separator: " ")
79 @AppStorage("themeFont") private var themeFont = ""
80 @AppStorage("themeFontSize") private var themeFontSize = 13
81 @AppStorage("themeLineSpacing") private var themeLineSpacing = 2
82 @AppStorage("themeHeadingStep") private var themeHeadingStep = 1
83
84 /// The theme's colors from config.toml with the type settings.
85 private var theme: ThemeSpec {
86 var spec = ConfigSync.shared.theme
87 spec.font = themeFont
88 spec.fontSize = themeFontSize
89 spec.lineSpacing = themeLineSpacing
90 spec.headingSizeStep = themeHeadingStep
91 return spec
92 }
93 /// The outline for a file that isn't org, off until asked for.
94 @State private var plainOutlineShown = false
95 @State private var showingImport = false
96 @AppStorage("showTabBar") private var showTabBar = false
97 /// Carets of restored buffers, shown when each first shows.
98 @State private var pendingCarets: [String: Int] = [:]
99 @State private var query = ""
100 @FocusState private var searchFocused: Bool
101 @Environment(\.openWindow) private var openWindow
102 @Environment(\.openSettings) private var openSettings
103
104 /// Whether the outline pane shows: remembered for org files, hidden by default for
105 /// other files, and always shown while search results are up.
106 private var outlineShown: Bool {
107 !query.isEmpty || (previewPath == nil && (session.isOrg ? orgOutlineShown : plainOutlineShown))
108 }
109
110 private func toggleOutline() {
111 if session.isOrg { orgOutlineShown.toggle() } else { plainOutlineShown.toggle() }
112 }
113
114 @ViewBuilder
115 private var detail: some View {
116 if let previewPath {
117 FilePreview(path: previewPath)
118 } else if session.path != nil {
119 VStack(spacing: 0) {
120 if showTabBar { BufferTabs(session: session) }
121 EditorView(session: session, commands: commands, keymap: keymap, modal: preset.isModal, optionAsMeta: OptionAsMeta(rawValue: optionAsMeta), options: options, showMarkup: showMarkup, showLineNumbers: showLineNumbers, theme: theme, onAppCommand: perform, onExternal: runExternal, knownTags: { [index = workspace.index] in (try? index.tags()) ?? [] })
122 }
123 .safeAreaInset(edge: .bottom, spacing: 0) {
124 VStack(spacing: 0) {
125 ModeLine(session: session, commands: commands, clock: clock, perform: perform)
126 EchoArea(commands: commands)
127 }
128 }
129 } else {
130 ContentUnavailableView(
131 workspace.roots.isEmpty ? "Add a folder of org files" : "Choose a file",
132 systemImage: "doc.text",
133 description: Text(workspace.roots.isEmpty ? "File ▸ Add Folder… (⇧⌘O)" : "Or press ⌘P to open one by name.")
134 )
135 }
136 }
137
138 @ToolbarContentBuilder
139 private var toolbarItems: some ToolbarContent {
140 ToolbarItem(placement: .navigation) {
141 Button(outlineShown ? "Hide Outline" : "Show Outline", systemImage: "list.bullet.indent") { toggleOutline() }
142 .help(outlineShown ? "Hide the outline (⌥⌘O)" : "Show the outline (⌥⌘O)")
143 .disabled(!query.isEmpty || previewPath != nil || session.path == nil)
144 }
145 if workspace.isIndexing {
146 ToolbarItem { ProgressView().controlSize(.small) }
147 }
148 if let running = clock.running {
149 ToolbarItem {
150 Menu {
151 Button("Clock Out") { perform("app.clock.out") }
152 Button("Cancel Clock") { perform("app.clock.cancel") }
153 Button("Go to Clocked Entry") { perform("app.clock.goto") }
154 Divider()
155 Button("Clock In to Recent Entry…") { perform("app.clock.in-recent") }
156 Button("Go to Recent Clocked Entry…") { perform("app.clock.goto-recent") }
157 RecentClocks(clock: clock) { perform($0) }
158 } label: {
159 TimelineView(.periodic(from: .now, by: 30)) { context in
160 Text("⏱ \(running.heading) \(clockElapsed(running, now: context.date))").lineLimit(1)
161 }
162 }
163 .help("Clocked in since \(running.startedAt.formatted(date: .omitted, time: .shortened))")
164 }
165 }
166 if session.conflict != nil {
167 ToolbarItem {
168 Button("Conflict", systemImage: "exclamationmark.triangle") { commands.showingConflict = true }
169 .help("The file changed on disk, and the changes conflict with yours")
170 }
171 }
172 }
173
174 private var main: some View {
175 NavigationSplitView {
176 Sidebar(workspace: workspace, session: session, selection: $selectedFile) { commands.showingFolderPicker = true }
177 .navigationSplitViewColumnWidth(min: 200, ideal: 260)
178 } detail: {
179 HStack(spacing: 0) {
180 if outlineShown {
181 Group {
182 if query.isEmpty {
183 VStack(spacing: 0) {
184 OutlineColumn(session: session)
185 if backlinksShown, session.isOrg {
186 Divider()
187 BacklinksPane(workspace: workspace, session: session, commands: commands) { location in
188 selectedFile = location.path
189 session.show(location)
190 }
191 .frame(height: 200)
192 }
193 }
194 } else {
195 SearchResults(results: workspace.search(query, overlay: workspace.overlay(session.openDocuments))) { location in
196 selectedFile = location.path
197 session.show(location)
198 }
199 }
200 }
201 .frame(width: CGFloat(outlineWidth))
202 PaneDivider(width: $outlineWidth, range: 160...400)
203 }
204 detail
205 .frame(maxWidth: .infinity)
206 .inspector(isPresented: $inspectorShown) {
207 InspectorPane(session: session, commands: commands)
208 .inspectorColumnWidth(min: 240, ideal: 340, max: 600)
209 }
210 }
211 }
212 .navigationTitle(previewPath.map { ($0 as NSString).lastPathComponent } ?? session.path.map(session.bufferName) ?? "Orgstar")
213 .navigationSubtitle(session.isReadOnly ? "Read-only: not UTF-8" : "")
214 .searchable(text: $query, placement: .toolbar, prompt: "Search notes")
215 .searchFocused($searchFocused)
216 .toolbar { toolbarItems }
217 .onChange(of: session.path) { plainOutlineShown = false }
218 .onChange(of: ScanRules(hiddenFiles: showHiddenFiles, ignoredFolders: Set(ignoredFolders.split(separator: " ").map(String.init))), initial: true) { _, rules in
219 workspace.scanRules = rules
220 }
221 .onChange(of: selectedFile) { old, path in
222 guard let path else { return }
223 if !DocumentSession.isOrgPath(path), !FileTypes.isText(path) {
224 previewPath = path
225 return
226 }
227 previewPath = nil
228 guard path != session.path else { return }
229 session.open(path)
230 }
231 .onChange(of: session.path) {
232 // Buffers switched by keys show in the sidebar too; a restored caret shows once.
233 if let path = session.path, selectedFile != path { selectedFile = path }
234 if let path = session.path, let caret = pendingCarets.removeValue(forKey: path) { session.reveal(caret) }
235 BufferRestore.save(session)
236 // Syncthing's conflict copies of the file.
237 let copies = session.syncConflictCopies().count
238 if copies > 0 { commands.show("\(copies) sync conflict \(copies == 1 ? "copy" : "copies") of this file; Resolve Sync Conflicts compares them.") }
239 }
240 .onChange(of: session.openPaths) { BufferRestore.save(session) }
241 .onChange(of: saveMode, initial: true) { _, mode in session.saveMode = mode }
242 .onChange(of: options, initial: true) { _, options in session.options = options }
243 .onChange(of: preset, initial: true) { loadKeymap() }
244 .sheet(isPresented: $showingImport) { EmacsImportView(workspace: workspace) }
245 .sheet(item: $panel) { panel in
246 switch panel {
247 case .columns(_, let view):
248 ColumnViewSheet(view: view) { offset in commands.editor?.reveal(offset) }
249 case .export(_, let source):
250 ExportSheet(source: source) { format, destination, open in export(format, to: destination, open: open) }
251 case .conflict:
252 ConflictSheet(session: session)
253 case .syncCopies:
254 SyncConflictSheet(session: session) { commands.show($0) }
255 case .recovery:
256 RecoverySheet(session: session) { commands.show($0) }
257 }
258 }
259 .sheet(item: $blockEdit) { request in
260 BlockEditorView(edit: request.edit) { content in
261 blockEdit = nil
262 guard let content else { return }
263 commands.editor?.perform(ReplaceBlockLines(edit: request.edit, content: content))
264 }
265 }
266 .sheet(isPresented: $commands.showingPalette) {
267 PaletteView(commands: commands) { id in
268 commands.showingPalette = false
269 // After the sheet closes, so app commands can present their own.
270 DispatchQueue.main.async { perform(id) }
271 }
272 }
273 .onChange(of: session.conflict) { _, conflict in
274 if conflict != nil { commands.showingConflict = true }
275 }
276 .onChange(of: commands.showingConflict) { _, showing in
277 guard showing else { return }
278 commands.showingConflict = false
279 if session.conflict != nil { panel = .conflict(UUID()) }
280 }
281 .onChange(of: workspace.changedFile?.version) {
282 if let path = workspace.changedFile?.path { session.fileChanged(path) }
283 }
284 }
285
286 var body: some View {
287 main
288 .onChange(of: ClockMenuState(running: clock.running, history: clock.history), initial: true) { _, state in
289 if statusItem == nil { statusItem = ClockStatusItem { commands.run($0) } }
290 statusItem?.update(state.running, recent: state.history.map(\.title))
291 }
292 .onChange(of: globalCapture, initial: true) { _, enabled in
293 hotKey?.unregister()
294 hotKey = enabled ? GlobalHotKey { perform("app.capture") } : nil
295 }
296 .onChange(of: commands.runRequest?.serial) {
297 if let id = commands.runRequest?.id { perform(id) }
298 }
299 .onChange(of: ConfigSync.shared.problems, initial: true) { _, problems in
300 if let first = problems.first {
301 commands.show(first + (problems.count > 1 ? " (and \(problems.count - 1) more)" : ""))
302 }
303 }
304 .onChange(of: ConfigSync.shared.changedFile?.serial) {
305 if ConfigSync.shared.changedFile?.name == "keymap.toml" { loadKeymap() }
306 }
307 .onChange(of: commands.jumpRequest?.id) {
308 guard let request = commands.jumpRequest else { return }
309 if request.path != session.path {
310 session.open(request.path)
311 selectedFile = request.path
312 }
313 session.reveal(request.offset)
314 }
315 .onChange(of: commands.focusSearch) { _, focus in
316 if focus {
317 searchFocused = true
318 commands.focusSearch = false
319 }
320 }
321 .fileImporter(isPresented: $commands.showingFolderPicker, allowedContentTypes: [.folder]) { result in
322 guard case .success(let url) = result else { return }
323 Task {
324 do { try await workspace.addRoot(url) } catch { workspace.lastError = error.localizedDescription }
325 }
326 }
327 .sheet(isPresented: $commands.showingQuickOpen) {
328 QuickOpenView(workspace: workspace) { entry in
329 selectedFile = entry.path
330 commands.showingQuickOpen = false
331 }
332 }
333 .alert("Orgstar", isPresented: errorShown) {
334 Button("OK") {
335 workspace.lastError = nil
336 session.lastError = nil
337 }
338 } message: {
339 Text(workspace.lastError ?? session.lastError ?? "")
340 }
341 .task(id: ReminderKey(
342 enabled: remindersEnabled, lead: reminderLead, subfolders: agendaSubfolders, files: workspace.files.count,
343 changed: workspace.changedFile?.version, edits: session.editVersion, hour: hour
344 )) {
345 await updateReminders()
346 }
347 .task {
348 while !Task.isCancelled {
349 try? await Task.sleep(for: .seconds(3600))
350 hour += 1
351 }
352 }
353 // `org-resolve-clocks-if-idle`, checked every minute while a clock runs.
354 .task(id: "\(clock.running?.start ?? "") \(clockIdleTime)") {
355 guard clock.running != nil, clockIdleTime > 0 else { return }
356 while !Task.isCancelled {
357 try? await Task.sleep(for: .seconds(60))
358 guard !Task.isCancelled, clock.running != nil, !clock.isResolving else { continue }
359 let idle = ClockIdle.seconds()
360 guard idle > Double(clockIdleTime * 60) else { continue }
361 NSApp.requestUserAttention(.informationalRequest)
362 report(await clock.resolveIdle(session, idleSince: Date().addingTimeInterval(-idle), ask: askClock))
363 }
364 }
365 .task {
366 DevelopmentHooks.scheduleSnapshot()
367 pendingCarets = BufferRestore.restore(session)
368 if let path = session.path, let caret = pendingCarets.removeValue(forKey: path) { session.reveal(caret) }
369 // Files handed over at launch open after the restored buffers, and show.
370 for path in AppDelegate.pendingOpens { session.open(path) }
371 AppDelegate.pendingOpens = []
372 for link in AppDelegate.pendingLinks + [DevelopmentHooks.urlToOpen].compactMap({ $0 }) { commands.handle(protocolURL: link) }
373 AppDelegate.pendingLinks = []
374 if let path = DevelopmentHooks.fileToOpen { selectedFile = path }
375 if let root = DevelopmentHooks.rootToAdd { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
376 if let commandList = DevelopmentHooks.commandToRun {
377 // The file opened above needs its editor first.
378 for _ in 0..<20 where DevelopmentHooks.fileToOpen != nil && commands.editor == nil { try? await Task.sleep(for: .milliseconds(100)) }
379 for command in commandList.split(separator: ",") { perform(String(command)) }
380 for answer in DevelopmentHooks.answers {
381 for _ in 0..<20 where commands.prompt == nil { try? await Task.sleep(for: .milliseconds(100)) }
382 commands.answer(answer)
383 }
384 }
385 if let id = DevelopmentHooks.windowToOpen {
386 if id == "settings" { openSettings() } else { openWindow(id: id) }
387 }
388 await workspace.refresh()
389 workspace.startWatching()
390 }
391 }
392
393 /// Writes the export beside the file, as Emacs's export dispatcher does, or to
394 /// `destination`, and opens it with `open`.
395 private func export(_ format: String, to destination: URL? = nil, open: Bool = false) {
396 guard let path = session.path, let text = session.document?.text else {
397 commands.show("No file is open")
398 return
399 }
400 let url = URL(fileURLWithPath: path)
401 let base = url.deletingPathExtension()
402 let defaults = Preferences.orgSettings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
403 let open = open || format == "html-open"
404 switch format {
405 case "html", "html-open", "markdown":
406 let target = destination ?? base.appendingPathExtension(format == "markdown" ? "md" : "html")
407 let content = format == "markdown"
408 ? MarkdownExport.document(text, settings: defaults, path: path)
409 : HTMLExport.page(text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path)
410 do {
411 try content.write(to: target, atomically: true, encoding: .utf8)
412 commands.show("Exported to \(target.lastPathComponent)")
413 if open { NSWorkspace.shared.open(target) }
414 } catch {
415 commands.show("Can't write \(target.lastPathComponent): \(error.localizedDescription)")
416 }
417 default:
418 let functions = ["pdf": "org-latex-export-to-pdf", "odt": "org-odt-export-to-odt", "latex": "org-latex-export-to-latex", "text": "org-ascii-export-to-ascii"]
419 guard let function = functions[format] else { return }
420 commands.show("Exporting with Emacs…")
421 commands.runInEmacs {
422 do {
423 var written = URL(fileURLWithPath: try await EmacsRunner.export(text: text, path: path, function: function))
424 if let destination, destination.standardizedFileURL != written.standardizedFileURL {
425 try? FileManager.default.removeItem(at: destination)
426 try FileManager.default.moveItem(at: written, to: destination)
427 written = destination
428 }
429 commands.show("Exported to \(written.lastPathComponent)")
430 if open { NSWorkspace.shared.open(written) }
431 } catch is CancellationError {
432 commands.show("Export canceled")
433 } catch {
434 commands.show("\(error)")
435 }
436 }
437 }
438 }
439
440 /// Work a command hands to the platform: tables recalculated in Emacs.
441 private func runExternal(_ request: ExternalRequest) {
442 switch request {
443 case .openLink(let link):
444 if let message = LinkOpener.open(link, session: session, workspace: workspace) { commands.show(message) }
445 case .tangle(let scope):
446 commands.show(session.tangle(scope))
447 case .agenda(let start, let days):
448 commands.agendaRequest = (start, days)
449 openWindow(id: "agenda")
450 case .editBlock(let edit):
451 blockEdit = BlockEditRequest(edit: edit)
452 case .columnView(let view):
453 panel = .columns(UUID(), view)
454 case .emacsTable(let table, let point, let form, let reason, let lisp):
455 let run = {
456 commands.show("Recalculating in Emacs (\(reason))…")
457 commands.runInEmacs { commands.show(await session.recalculateInEmacs(table: table, point: point, form: form)) }
458 }
459 guard lisp, let path = session.path, let text = session.document?.text else { return run() }
460 let content = (text as NSString).substring(with: NSRange(location: table.lowerBound, length: min((text as NSString).length, table.upperBound + 2000) - table.lowerBound))
461 if trust.isTrusted(path: path, content: content) { return run() }
462 commands.ask(Prompt(key: "confirm", message: "This table's formulas run Lisp. Run them? (yes, no, always)", choices: ["yes", "no", "always"])) { answer in
463 switch answer {
464 case "always":
465 trust.trust(path: path, content: content)
466 run()
467 case "yes": run()
468 default: commands.show("Not recalculated")
469 }
470 }
471 case .babel(let job):
472 let run = {
473 commands.show("Running \(job.language) block… (⌘. to cancel)")
474 session.startBabel(job) { commands.show($0) }
475 }
476 guard let path = session.path else { return }
477 if !job.alwaysAsk, trust.isTrusted(path: path, content: job.blockText) { return run() }
478 let choices = job.alwaysAsk ? ["yes", "no"] : ["yes", "no", "always"]
479 commands.ask(Prompt(key: "confirm", message: "Run this \(job.language) block? (\(choices.joined(separator: ", ")))", choices: choices)) { answer in
480 switch answer {
481 case "always":
482 trust.trust(path: path, content: job.blockText)
483 run()
484 case "yes": run()
485 default: commands.show("Not run")
486 }
487 }
488 }
489 }
490
491 private struct ReminderKey: Hashable {
492 var enabled: Bool
493 var lead: Int
494 var subfolders: Bool
495 var files: Int
496 var changed: Int?
497 var edits: Int
498 var hour: Int
499 }
500
501 /// Sets the notifications for the next week's timed entries, once edits pause.
502 private func updateReminders() async {
503 guard let scheduler else { return }
504 guard remindersEnabled else {
505 await scheduler.clear()
506 return
507 }
508 try? await Task.sleep(for: .seconds(2))
509 guard !Task.isCancelled, !workspace.files.isEmpty else { return }
510 let agenda = reminderAgenda ?? AgendaModel(workspace: workspace)
511 reminderAgenda = agenda
512 agenda.includeSubfolders = agendaSubfolders
513 let open = session.openTexts
514 let reminders = await agenda.reminders(open: open, lead: reminderLead)
515 guard !Task.isCancelled else { return }
516 await scheduler.reconcile(reminders)
517 }
518
519 private func loadKeymap() {
520 let loaded = KeymapLoader.load(preset, commands: Set(EditorCommands.all.map(\.id)))
521 keymap = loaded.keymap
522 commands.keymap = loaded.keymap
523 commands.modal = preset.isModal
524 if let first = loaded.problems.first {
525 let more = loaded.problems.count > 1 ? " (and \(loaded.problems.count - 1) more)" : ""
526 commands.show("keymap.toml: \(first)\(more)")
527 }
528 }
529
530 /// `SPC b b`: open buffers, most recent first, by name (with the folder when names repeat).
531 private func switchBuffer() {
532 let paths = session.recentPaths.dropFirst() + session.recentPaths.prefix(1)
533 let labels = paths.map(session.bufferName)
534 guard !labels.isEmpty else { return commands.show("No buffers are open") }
535 commands.ask(Prompt(key: "buffer", message: "Switch to buffer:", choices: labels)) { answer in
536 guard let answer, let index = labels.firstIndex(of: answer) else { return }
537 session.open(Array(paths)[index])
538 }
539 }
540
541 /// Runs a command from a key, the palette or the Org menu.
542 private func perform(_ id: String) {
543 let orgOnly = ["app.refile", "app.archive", "app.clock.in", "app.clock.default"].contains(id) || id.hasPrefix("app.export.") || id.hasPrefix("org.")
544 if orgOnly, !session.isOrg {
545 commands.show("Not an org file")
546 return
547 }
548 switch id {
549 case "app.save":
550 if !session.save(), session.conflict != nil { commands.showingConflict = true }
551 case "app.quit": NSApp.terminate(nil)
552 case "app.save-all":
553 if !session.saveAll(), session.conflict != nil { commands.showingConflict = true }
554 case "app.buffer.switch": switchBuffer()
555 case "app.buffer.next": session.cycle(1)
556 case "app.buffer.previous": session.cycle(-1)
557 case "app.buffer.last": session.showPrevious()
558 case "app.buffer.kill":
559 guard let path = session.path else {
560 NSApp.keyWindow?.performClose(nil)
561 return
562 }
563 if UnsavedChanges.resolve(session) { session.kill(path) }
564 case "app.buffer.kill-others":
565 let others = session.openPaths.filter { $0 != session.path }
566 if UnsavedChanges.resolve(session, paths: others) { others.forEach(session.kill) }
567 case "app.buffer.kill-all":
568 let all = session.openPaths
569 if UnsavedChanges.resolve(session, paths: all) { all.forEach(session.kill) }
570 case "app.toggle-tab-bar": showTabBar.toggle()
571 case "app.babel.cancel":
572 if session.isRunningBabel {
573 session.cancelBabel()
574 } else if let task = commands.emacsTask {
575 task.cancel()
576 } else {
577 commands.show("Nothing is running")
578 }
579 case "app.toggle-outline": toggleOutline()
580 case "app.toggle-backlinks": backlinksShown.toggle()
581 case "app.toggle-inspector": inspectorShown.toggle()
582 case "app.toggle-markup": showMarkup.toggle()
583 case "app.toggle-line-numbers": showLineNumbers.toggle()
584 case "app.import-emacs": showingImport = true
585 case "app.edit-config": commands.jump(path: UserConfig.configFile.path, offset: 0)
586 case "app.quick-open": commands.showingQuickOpen = true
587 case "app.palette": commands.showingPalette = true
588 case "app.search": commands.focusSearch = true
589 case "app.reload-keymap":
590 loadKeymap()
591 commands.show("Keymap reloaded")
592 case "app.refile":
593 let targets = workspace.refileTargets(openPath: session.path, document: session.document)
594 commands.ask(Prompt(key: "refile", message: "Refile to:", choices: targets.map(\.label))) { answer in
595 guard let answer, let target = targets.first(where: { $0.label == answer }) else { return }
596 if let message = session.refile(to: target) { commands.show(message) }
597 }
598 case "app.archive":
599 if let message = session.archive() { commands.show(message) }
600 case "app.table-import":
601 // `org-table-import`: a TSV, CSV or space-separated file becomes a table at point.
602 guard let editor = commands.editor else { return commands.show("No file is open") }
603 let panel = NSOpenPanel()
604 panel.allowedContentTypes = [.commaSeparatedText, .tabSeparatedText, .plainText]
605 guard panel.runModal() == .OK, let url = panel.url else { return }
606 guard let contents = try? String(contentsOf: url, encoding: .utf8) else { return commands.show("Can't read \(url.lastPathComponent)") }
607 editor.perform(ImportTable(contents: contents))
608 case "app.table-export":
609 // `org-table-export`: CSV for a .csv name, else TSV.
610 guard let editor = commands.editor else { return commands.show("No file is open") }
611 let context = editor.context()
612 guard ImportTable.exportText(context.text, at: context.caret, path: "") != nil else { return commands.show("No table at point") }
613 let panel = NSSavePanel()
614 panel.nameFieldStringValue = "table.csv"
615 guard panel.runModal() == .OK, let url = panel.url,
616 let text = ImportTable.exportText(context.text, at: context.caret, path: url.path) else { return }
617 do {
618 try text.write(to: url, atomically: true, encoding: .utf8)
619 commands.show("Export done.")
620 } catch {
621 commands.show("File not written: \(error.localizedDescription)")
622 }
623 case "org.subtree.paste":
624 guard let text = NSPasteboard.general.string(forType: .string) else { return commands.show("The clipboard is empty") }
625 commands.editor?.perform(PasteSubtree(text: text))
626 case "org.link.insert":
627 commands.editor?.perform(InsertLink(stored: commands.storedLinks, file: session.path))
628 case "org.link.store":
629 guard let editor = commands.editor, let path = session.path else { return commands.show("No method for storing a link from this buffer") }
630 commands.storeLink(Links.store(in: editor.context(), path: Links.abbreviate(path, home: NSHomeDirectory())))
631 case "org.id.store-link":
632 guard let editor = commands.editor, let path = session.path else { return }
633 if case .commit = editor.perform(CreateID()),
634 let link = Links.storeID(in: editor.context(), fileName: (path as NSString).lastPathComponent) {
635 commands.storeLink(link)
636 }
637 case "app.agenda":
638 openWindow(id: "agenda")
639 case "app.clock.in":
640 clockIn(.caret)
641 case "app.clock.in-recent":
642 clockIn(.select)
643 case "app.clock.in-last":
644 clockIn(.last)
645 case let id where id.hasPrefix("app.clock.history."):
646 if let index = Int(id.dropFirst("app.clock.history.".count)), index < clock.history.count { clockIn(.task(clock.history[index])) }
647 case "app.clock.out":
648 commands.show(clock.clockOut(session))
649 case "app.clock.cancel":
650 commands.show(clock.clockOut(session, cancel: true))
651 case "app.clock.goto":
652 let found = clock.goto(session)
653 if let location = found.location { commands.jump(path: location.path, offset: location.offset) }
654 if let message = found.message { commands.show(message) }
655 case "app.clock.goto-recent":
656 Task {
657 let found = await clock.gotoRecent(session, ask: askClock)
658 if let location = found.location { commands.jump(path: location.path, offset: location.offset) }
659 if let message = found.message { commands.show(message) }
660 }
661 case "app.clock.default":
662 commands.show(clock.markDefault(session))
663 case "app.clock.resolve":
664 Task { report(await clock.resolveOpenClocks(session, paths: orgFiles, ask: askClock)) }
665 case "app.clock.report":
666 openWindow(id: "clock-report")
667 case "app.board":
668 openWindow(id: "board")
669 case "app.capture":
670 NSApp.activate()
671 openWindow(id: "capture")
672 case "app.revert":
673 // `:e`: the file as it is on disk; unsaved changes go to recovery.
674 guard session.path != nil else { return commands.show("No file is open") }
675 session.useDiskVersion()
676 commands.show("Reverted to the file on disk")
677 case "app.sync-conflicts":
678 guard session.path != nil else { return commands.show("No file is open") }
679 panel = .syncCopies(UUID())
680 case "app.recovery":
681 guard session.path != nil else { return commands.show("No file is open") }
682 panel = .recovery(UUID())
683 case "app.export-dialog":
684 guard let path = session.path else { return commands.show("No file is open") }
685 panel = .export(UUID(), URL(fileURLWithPath: path))
686 case let id where id.hasPrefix("app.export."):
687 export(String(id.dropFirst("app.export.".count)))
688 default:
689 if let editor = commands.editor { editor.run(id) } else { commands.show("No file is open") }
690 }
691 }
692
693 /// Clock questions in the echo area.
694 private var askClock: ClockModel.Ask {
695 { [commands] prompt in
696 await withCheckedContinuation { continuation in
697 commands.ask(prompt) { continuation.resume(returning: $0) }
698 }
699 }
700 }
701
702 /// The files `org-resolve-clocks` looks through: the workspace's org files.
703 private var orgFiles: [String] { workspace.files.filter { $0.kind == .org }.map(\.path) }
704
705 private func clockIn(_ target: ClockModel.Target) {
706 Task { report(await clock.clockIn(session, target: target, paths: orgFiles, ask: askClock)) }
707 }
708
709 /// The last message of a clock command, and the clock to show for `j`.
710 private func report(_ outcome: ClockModel.Outcome) {
711 if let jump = outcome.jump { commands.jump(path: jump.path, offset: jump.offset) }
712 if let message = outcome.messages.last(where: { !$0.isEmpty }) { commands.show(message) }
713 }
714
715 private var errorShown: Binding<Bool> {
716 Binding(get: { workspace.lastError != nil || session.lastError != nil }, set: { _ in })
717 }
718}
719
720struct Sidebar: View {
721 let workspace: WorkspaceModel
722 let session: DocumentSession
723 @Binding var selection: String?
724 var addFolder: () -> Void = {}
725 /// Folders shown collapsed, by path, one per line.
726 @AppStorage("collapsedFolders") private var collapsedText = ""
727 @State private var removing: String?
728 /// A file operation waiting for a name or a confirmation.
729 @Environment(\.orgTheme) private var theme
730 @State var pending: FileOperation?
731 @State var name = ""
732 @State var failure: String?
733
734 private var collapsed: Set<String> { Set(collapsedText.split(separator: "\n").map(String.init)) }
735
736 private func expanded(_ root: String) -> Binding<Bool> {
737 Binding {
738 !collapsed.contains(root)
739 } set: { isExpanded in
740 var set = collapsed
741 if isExpanded { set.remove(root) } else { set.insert(root) }
742 collapsedText = set.sorted().joined(separator: "\n")
743 }
744 }
745
746 var body: some View {
747 List(selection: $selection) {
748 ForEach(workspace.rootPaths, id: \.self) { root in
749 Section(isExpanded: expanded(root)) {
750 OutlineGroup(workspace.tree(forRoot: root).children ?? [], children: \.children) { node in
751 Label(node.name, systemImage: icon(node))
752 .foregroundStyle(node.file?.kind == .conflict ? .orange : node.isDownloading ? .secondary : theme.color("sidebar-foreground") ?? .primary)
753 .help(node.isDownloading ? "Downloading from iCloud" : "")
754 .tag(node.file?.path)
755 .contextMenu { fileMenu(node) }
756 }
757 } header: {
758 Text((root as NSString).lastPathComponent)
759 .foregroundStyle(theme.color("sidebar-header") ?? .secondary)
760 .help(root)
761 .contextMenu { folderMenu(root) }
762 }
763 }
764 }
765 .listStyle(.sidebar)
766 .themedListBackground(theme.color("sidebar-background"))
767 .safeAreaInset(edge: .bottom, spacing: 0) {
768 HStack(spacing: 4) {
769 Button("Add Folder…", systemImage: "plus", action: addFolder)
770 .help("Add a folder (⇧⌘O)")
771 Menu {
772 ForEach(workspace.rootPaths, id: \.self) { root in
773 Button((root as NSString).lastPathComponent) { removing = root }
774 }
775 } label: {
776 Label("Remove Folder", systemImage: "minus")
777 }
778 .menuIndicator(.hidden)
779 .fixedSize()
780 .disabled(workspace.rootPaths.isEmpty)
781 .help("Remove a folder from the sidebar")
782 Spacer()
783 }
784 .labelStyle(.iconOnly)
785 .buttonStyle(.borderless)
786 .menuStyle(.borderlessButton)
787 .padding(.horizontal, 10)
788 .padding(.vertical, 6)
789 }
790 .confirmationDialog(
791 "Remove “\(removing.map { ($0 as NSString).lastPathComponent } ?? "")” from the sidebar?",
792 isPresented: Binding { removing != nil } set: { if !$0 { removing = nil } }
793 ) {
794 Button("Remove") {
795 if let root = removing { try? workspace.removeRoot(path: root) }
796 removing = nil
797 }
798 } message: {
799 Text("The folder and its files stay on disk.")
800 }
801 .fileOperations(self)
802 }
803
804 @ViewBuilder
805 private func folderMenu(_ root: String) -> some View {
806 Button("New File…") { ask(.create(folder: root)) }
807 Divider()
808 Button(collapsed.contains(root) ? "Expand" : "Collapse") { expanded(root).wrappedValue.toggle() }
809 Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: root)]) }
810 Divider()
811 Button("Remove from Sidebar…") { removing = root }
812 }
813
814 private func icon(_ node: FileTreeNode) -> String {
815 if node.isDownloading { return "icloud.and.arrow.down" }
816 guard let file = node.file else { return "folder" }
817 switch file.kind {
818 case .org: return "doc.text"
819 case .archive: return "archivebox"
820 case .conflict: return "exclamationmark.triangle"
821 case .other:
822 guard let type = UTType(filenameExtension: (file.path as NSString).pathExtension) else { return "doc" }
823 if type.conforms(to: .image) { return "photo" }
824 if type.conforms(to: .pdf) { return "doc.richtext" }
825 if type.conforms(to: .audiovisualContent) { return "play.rectangle" }
826 if type.conforms(to: .sourceCode) || type.conforms(to: .script) { return "chevron.left.forwardslash.chevron.right" }
827 if type.conforms(to: .text) { return "doc.plaintext" }
828 return "doc"
829 }
830 }
831}
832
833struct OutlineColumn: View {
834 let session: DocumentSession
835 @Environment(\.orgTheme) private var theme
836
837 var body: some View {
838 List(Array(session.outline.enumerated()), id: \.element.start) { _, entry in
839 Button {
840 session.reveal(entry.start)
841 } label: {
842 Text(entry.title.isEmpty ? "(untitled)" : entry.title)
843 .foregroundStyle(theme.color("sidebar-foreground") ?? .primary)
844 .lineLimit(1)
845 .padding(.leading, CGFloat(entry.level - 1) * 12)
846 }
847 .buttonStyle(.plain)
848 }
849 .themedListBackground(theme.color("sidebar-background"))
850 .overlay {
851 if session.path != nil, !session.isOrg {
852 ContentUnavailableView("No outline", systemImage: "doc.plaintext", description: Text("Only org files have an outline."))
853 } else if session.path != nil, session.outline.isEmpty {
854 ContentUnavailableView("No headings", systemImage: "list.bullet.indent")
855 }
856 }
857 }
858}
859
860struct SearchResults: View {
861 let results: [HeadingLocation]
862 let open: (HeadingLocation) -> Void
863
864 var body: some View {
865 List(results, id: \.self) { location in
866 Button {
867 open(location)
868 } label: {
869 VStack(alignment: .leading, spacing: 2) {
870 Text(location.title.isEmpty ? "(untitled)" : location.title).lineLimit(1)
871 Text((location.path as NSString).lastPathComponent).font(.caption).foregroundStyle(.secondary)
872 }
873 }
874 .buttonStyle(.plain)
875 }
876 .overlay {
877 if results.isEmpty { ContentUnavailableView.search }
878 }
879 }
880}
881
882struct QuickOpenView: View {
883 let workspace: WorkspaceModel
884 let open: (FileEntry) -> Void
885 @State private var query = ""
886 /// The highlighted match, moved by ↑/↓ or C-p/C-n and opened by Return.
887 @State private var selected = 0
888 @Environment(\.dismiss) private var dismiss
889
890 var body: some View {
891 let matches = workspace.quickOpen(query)
892 let current = min(selected, matches.count - 1)
893 VStack(spacing: 0) {
894 TextField("Open file", text: $query)
895 .textFieldStyle(.plain)
896 .font(.title3)
897 .padding(12)
898 .onSubmit { if current >= 0 { open(matches[current]) } }
899 .onKeyPress(phases: .down) { press in
900 let control = press.modifiers == .control
901 let step = if press.key == .downArrow || control && press.characters == "n" { 1 }
902 else if press.key == .upArrow || control && press.characters == "p" { -1 } else { 0 }
903 guard step != 0 else { return .ignored }
904 selected = max(0, min(current + step, matches.count - 1))
905 return .handled
906 }
907 .onChange(of: query) { selected = 0 }
908 Divider()
909 ScrollViewReader { proxy in
910 List(matches.indices, id: \.self) { index in
911 let entry = matches[index]
912 Button {
913 open(entry)
914 } label: {
915 VStack(alignment: .leading, spacing: 2) {
916 Text(entry.name)
917 Text(entry.relativePath).font(.caption).foregroundStyle(.secondary)
918 }
919 .frame(maxWidth: .infinity, alignment: .leading)
920 .contentShape(Rectangle())
921 }
922 .buttonStyle(.plain)
923 .listRowBackground(index == current ? Color.accentColor.opacity(0.25) : Color.clear)
924 .accessibilityAddTraits(index == current ? .isSelected : [])
925 }
926 .onChange(of: current) { if current >= 0 { proxy.scrollTo(current) } }
927 }
928 }
929 .frame(width: 520, height: 360)
930 .onExitCommand { dismiss() }
931 }
932}
933
934/// A divider that resizes the pane before it by dragging. An `HSplitView` inside the window's
935/// split view loops on its size constraints in short windows, so this sets a width instead.
936struct PaneDivider: View {
937 @Binding var width: Double
938 let range: ClosedRange<Double>
939 @State private var start: Double?
940
941 var body: some View {
942 Rectangle()
943 .fill(Color(nsColor: .separatorColor))
944 .frame(width: 1)
945 .frame(maxHeight: .infinity)
946 .overlay(Color.clear.frame(width: 7).contentShape(Rectangle()).onHover { inside in
947 if inside { NSCursor.resizeLeftRight.push() } else { NSCursor.pop() }
948 }
949 .gesture(DragGesture(minimumDistance: 1).onChanged { drag in
950 let base = start ?? width
951 start = base
952 width = min(max(base + drag.translation.width, range.lowerBound), range.upperBound)
953 }.onEnded { _ in start = nil }))
954 .accessibilityHidden(true)
955 }
956}
957
958/// A tab for each open buffer: click to show it, × to close it, a dot for unsaved edits.
959struct BufferTabs: View {
960 let session: DocumentSession
961 @Environment(\.orgTheme) private var theme
962
963 var body: some View {
964 ScrollView(.horizontal, showsIndicators: false) {
965 HStack(spacing: 0) {
966 ForEach(session.openPaths, id: \.self) { path in
967 tab(path)
968 }
969 }
970 }
971 .frame(height: 28)
972 .background { Rectangle().fill(theme.color("modeline-background").map(AnyShapeStyle.init) ?? AnyShapeStyle(.bar)) }
973 .overlay(alignment: .bottom) { Divider() }
974 }
975
976 private func tab(_ path: String) -> some View {
977 let current = path == session.path
978 return HStack(spacing: 6) {
979 Text(session.bufferName(path))
980 .lineLimit(1)
981 .foregroundStyle(current ? .primary : .secondary)
982 .accessibilityAddTraits(current ? [.isButton, .isSelected] : .isButton)
983 .accessibilityAction { session.open(path) }
984 Button {
985 if path == session.path {
986 if UnsavedChanges.resolve(session) { session.kill(path) }
987 } else if UnsavedChanges.resolve(session, paths: [path]) {
988 session.kill(path)
989 }
990 } label: {
991 Image(systemName: session.dirtyPaths.contains(path) ? "circle.fill" : "xmark")
992 .font(.system(size: session.dirtyPaths.contains(path) ? 6 : 9, weight: .semibold))
993 .frame(width: 12, height: 12)
994 }
995 .buttonStyle(.borderless)
996 .help("Close")
997 .accessibilityLabel("Close \(session.bufferName(path))" + (session.dirtyPaths.contains(path) ? ", unsaved" : ""))
998 }
999 .font(.callout)
1000 .padding(.horizontal, 12)
1001 .frame(maxHeight: .infinity)
1002 // A shape, not a color: a color background runs up under the toolbar.
1003 .background { Rectangle().fill(current ? theme.color("background") ?? Color(nsColor: .textBackgroundColor) : .clear) }
1004 .overlay(alignment: .trailing) { Divider() }
1005 .contentShape(Rectangle())
1006 .onTapGesture { session.open(path) }
1007 .help(path)
1008 }
1009}
1010
1011enum Panel: Identifiable {
1012 case columns(UUID, ColumnView.View)
1013 case export(UUID, URL)
1014 case conflict(UUID)
1015 case syncCopies(UUID)
1016 case recovery(UUID)
1017
1018 var id: UUID {
1019 switch self {
1020 case .columns(let id, _), .export(let id, _), .conflict(let id), .syncCopies(let id), .recovery(let id): id
1021 }
1022 }
1023}
1024
1025struct BlockEditRequest: Identifiable {
1026 let id = UUID()
1027 let edit: BlockEdit
1028}