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