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