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