Sources/Orgstar/ContentView.swift
848 lines · 44856 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("clockIdleTime") private var clockIdleTime = 0
20 @AppStorage("agendaSubfolders") private var agendaSubfolders = false
21 @State private var reminderAgenda: AgendaModel?
22 @State private var trust = TrustStore()
23 @State private var hotKey: GlobalHotKey?
24 @State private var statusItem: ClockStatusItem?
25 @AppStorage("globalCapture") private var globalCapture = true
26 @State private var hour = 0
27 @AppStorage("saveMode") private var saveMode = SaveMode.automatic
28 @AppStorage("keymap") private var preset = KeymapPreset.emacs
29 @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
30 @State private var keymap = KeymapPreset.emacs.keymap
31 @AppStorage("tagsColumn") private var tagsColumn = -77
32 @AppStorage("headingAfterSubtree") private var headingAfterSubtree = true
33 @AppStorage("splitLine") private var splitLine = false
34 @AppStorage("alphabeticalLists") private var alphabeticalLists = true
35 @AppStorage("fillColumn") private var fillColumn = 80
36 @AppStorage("hiddenMarkers") private var hiddenMarkers = true
37 @AppStorage("prettyEntities") private var prettyEntities = true
38 @AppStorage("logDone") private var logDone = "nil"
39 @AppStorage("logIntoDrawer") private var logIntoDrawer = ""
40 @AppStorage("logReschedule") private var logReschedule = "nil"
41 @AppStorage("logRedeadline") private var logRedeadline = "nil"
42 @AppStorage("useSpeedCommands") private var useSpeedCommands = false
43 @AppStorage("startupWithInlineImages") private var startupWithInlineImages = false
44 @AppStorage("startupIndented") private var startupIndented = true
45 @AppStorage("hideLeadingStars") private var hideLeadingStars = false
46 @AppStorage("startupAlignAllTables") private var startupAlignAllTables = false
47 @AppStorage("startupTruncated") private var startupTruncated = false
48 @AppStorage("spellCheck") private var spellCheck = false
49 @AppStorage("electricPair") private var electricPair = true
50 @AppStorage("hideDrawerStartup") private var hideDrawerStartup = true
51 @AppStorage("hideBlockStartup") private var hideBlockStartup = false
52 @AppStorage("enforceTodoDependencies") private var enforceTodoDependencies = false
53 @AppStorage("enforceTodoCheckboxDependencies") private var enforceTodoCheckboxDependencies = false
54
55 private var options: EditingOptions {
56 Preferences.options(
57 tagsColumn: tagsColumn, headingAfterSubtree: headingAfterSubtree, splitLine: splitLine, alphabeticalLists: alphabeticalLists,
58 fillColumn: fillColumn, hiddenMarkers: hiddenMarkers, prettyEntities: prettyEntities, logDone: logDone, logIntoDrawer: logIntoDrawer,
59 hideDrawerStartup: hideDrawerStartup, hideBlockStartup: hideBlockStartup, logReschedule: logReschedule, logRedeadline: logRedeadline,
60 useSpeedCommands: useSpeedCommands, startupWithInlineImages: startupWithInlineImages,
61 startupIndented: startupIndented, hideLeadingStars: hideLeadingStars, startupAlignAllTables: startupAlignAllTables,
62 startupTruncated: startupTruncated, spellCheck: spellCheck, electricPair: electricPair,
63 enforceTodoDependencies: enforceTodoDependencies, enforceTodoCheckboxDependencies: enforceTodoCheckboxDependencies
64 )
65 }
66 /// A block being edited apart (`org-edit-special`).
67 @State private var blockEdit: BlockEditRequest?
68 /// A sheet a command opened: column view or the export dialog.
69 @State private var panel: Panel?
70
71 @State private var selectedFile: String?
72 /// A file that isn't text, shown as a preview instead of the open document.
73 @State private var previewPath: String?
74 @AppStorage("outlineShown") private var orgOutlineShown = true
75 @AppStorage("outlineWidth") private var outlineWidth = 220.0
76 @AppStorage("backlinksShown") private var backlinksShown = true
77 @AppStorage("inspectorShown") private var inspectorShown = false
78 @AppStorage("showMarkup") private var showMarkup = false
79 @AppStorage("showLineNumbers") private var showLineNumbers = true
80 @AppStorage("showHiddenFiles") private var showHiddenFiles = true
81 @AppStorage("ignoredFolders") private var ignoredFolders = ScanRules.defaultIgnoredFolders.sorted().joined(separator: " ")
82 @AppStorage("themeFont") private var themeFont = ""
83 @AppStorage("themeFontSize") private var themeFontSize = 13
84 @AppStorage("themeLineSpacing") private var themeLineSpacing = 2
85 @AppStorage("themeHeadingStep") private var themeHeadingStep = 1
86
87 /// The theme's colors from config.toml with the type settings.
88 private var theme: ThemeSpec {
89 var spec = ConfigSync.shared.theme
90 spec.font = themeFont
91 spec.fontSize = themeFontSize
92 spec.lineSpacing = themeLineSpacing
93 spec.headingSizeStep = themeHeadingStep
94 return spec
95 }
96 /// The outline for a file that isn't org, off until asked for.
97 @State private var plainOutlineShown = false
98 @State private var showingImport = false
99 @AppStorage("showTabBar") private var showTabBar = false
100 /// This window's panes.
101 @State private var window: WindowModel?
102
103 private var editorSettings: EditorSettings {
104 EditorSettings(keymap: keymap, modal: preset.isModal, optionAsMeta: OptionAsMeta(rawValue: optionAsMeta), options: options, showMarkup: showMarkup, showLineNumbers: showLineNumbers, theme: theme)
105 }
106
107 /// The window holding the focused pane: this one, or an editor window.
108 private var paneWindow: WindowModel? {
109 commands.store.window(of: session.focused.id) ?? window
110 }
111
112 /// Gives the focused pane's text view the keyboard, after a pane command moved the focus.
113 private func focusPane(_ window: WindowModel) {
114 let pane = window.focusedPane
115 session.focused = pane
116 if let path = pane.path, let textView = commands.store.textView(for: pane.id, path: path) {
117 textView.window?.makeFirstResponder(textView)
118 commands.editor = commands.store.editor(for: path)
119 } else {
120 commands.editor = nil
121 }
122 }
123 /// Carets of restored buffers, shown when each first shows.
124 @State private var pendingCarets: [String: Int] = [:]
125 @State private var query = ""
126 @FocusState private var searchFocused: Bool
127 @Environment(\.openWindow) private var openWindow
128 @Environment(\.openSettings) private var openSettings
129
130 /// Whether the outline pane shows: remembered for org files, hidden by default for
131 /// other files, and always shown while search results are up.
132 private var outlineShown: Bool {
133 !query.isEmpty || (previewPath == nil && (session.isOrg ? orgOutlineShown : plainOutlineShown))
134 }
135
136 private func toggleOutline() {
137 if session.isOrg { orgOutlineShown.toggle() } else { plainOutlineShown.toggle() }
138 }
139
140 @ViewBuilder
141 private var detail: some View {
142 if let previewPath {
143 FilePreview(path: previewPath)
144 } else if !session.openPaths.isEmpty, let window {
145 PaneLayoutView(layout: window.layout, window: window) { pane in
146 PaneCell(pane: pane, window: window, session: session, commands: commands, showTabBar: showTabBar, onAppCommand: perform)
147 }
148 .safeAreaInset(edge: .bottom, spacing: 0) {
149 VStack(spacing: 0) {
150 ModeLine(session: session, commands: commands, clock: clock, perform: perform)
151 EchoArea(commands: commands)
152 }
153 }
154 } else {
155 ContentUnavailableView(
156 workspace.roots.isEmpty ? "Add a folder of org files" : "Choose a file",
157 systemImage: "doc.text",
158 description: Text(workspace.roots.isEmpty ? "File ▸ Add Folder… (⇧⌘O)" : "Or press ⌘P to open one by name.")
159 )
160 }
161 }
162
163 @ToolbarContentBuilder
164 private var toolbarItems: some ToolbarContent {
165 ToolbarItem(placement: .navigation) {
166 Button(outlineShown ? "Hide Outline" : "Show Outline", systemImage: "list.bullet.indent") { toggleOutline() }
167 .help(outlineShown ? "Hide the outline (⌥⌘O)" : "Show the outline (⌥⌘O)")
168 .disabled(!query.isEmpty || previewPath != nil || session.path == nil)
169 }
170 if workspace.isIndexing {
171 ToolbarItem { ProgressView().controlSize(.small) }
172 }
173 if let running = clock.running {
174 ToolbarItem {
175 Menu {
176 Button("Clock Out") { perform("app.clock.out") }
177 Button("Cancel Clock") { perform("app.clock.cancel") }
178 Button("Go to Clocked Entry") { perform("app.clock.goto") }
179 Divider()
180 Button("Clock In to Recent Entry…") { perform("app.clock.in-recent") }
181 Button("Go to Recent Clocked Entry…") { perform("app.clock.goto-recent") }
182 RecentClocks(clock: clock) { perform($0) }
183 } label: {
184 TimelineView(.periodic(from: .now, by: 30)) { context in
185 Text("⏱ \(running.heading) \(clockElapsed(running, now: context.date))").lineLimit(1)
186 }
187 }
188 .help("Clocked in since \(running.startedAt.formatted(date: .omitted, time: .shortened))")
189 }
190 }
191 if session.conflict != nil {
192 ToolbarItem {
193 Button("Conflict", systemImage: "exclamationmark.triangle") { commands.showingConflict = true }
194 .help("The file changed on disk, and the changes conflict with yours")
195 }
196 }
197 }
198
199 private var main: some View {
200 NavigationSplitView {
201 Sidebar(workspace: workspace, session: session, selection: $selectedFile) { commands.showingFolderPicker = true }
202 .navigationSplitViewColumnWidth(min: 200, ideal: 260)
203 } detail: {
204 HStack(spacing: 0) {
205 if outlineShown {
206 Group {
207 if query.isEmpty {
208 VStack(spacing: 0) {
209 OutlineColumn(session: session)
210 if backlinksShown, session.isOrg {
211 Divider()
212 BacklinksPane(workspace: workspace, session: session, commands: commands) { location in
213 selectedFile = location.path
214 session.show(location)
215 }
216 .frame(height: 200)
217 }
218 }
219 } else {
220 SearchResults(results: workspace.search(query, overlay: workspace.overlay(session.openDocuments))) { location in
221 selectedFile = location.path
222 session.show(location)
223 }
224 }
225 }
226 .frame(width: CGFloat(outlineWidth))
227 PaneDivider(width: $outlineWidth, range: 160...400)
228 }
229 detail
230 .frame(maxWidth: .infinity)
231 .inspector(isPresented: $inspectorShown) {
232 InspectorPane(session: session, commands: commands)
233 .inspectorColumnWidth(min: 240, ideal: 340, max: 600)
234 }
235 }
236 }
237 .navigationTitle(previewPath.map { ($0 as NSString).lastPathComponent } ?? session.path.map(session.bufferName) ?? "orgstar")
238 .navigationSubtitle(session.isReadOnly ? "Read-only: not UTF-8" : "")
239 .searchable(text: $query, placement: .toolbar, prompt: "Search notes")
240 .searchFocused($searchFocused)
241 .toolbar { toolbarItems }
242 .onChange(of: session.path) { plainOutlineShown = false }
243 .onChange(of: ScanRules(hiddenFiles: showHiddenFiles, ignoredFolders: Set(ignoredFolders.split(separator: " ").map(String.init))), initial: true) { _, rules in
244 workspace.scanRules = rules
245 }
246 .onChange(of: selectedFile) { old, path in
247 guard let path else { return }
248 if !DocumentSession.isOrgPath(path), !FileTypes.isText(path) {
249 previewPath = path
250 return
251 }
252 previewPath = nil
253 guard path != session.path else { return }
254 session.open(path)
255 }
256 .onChange(of: session.path) {
257 // Buffers switched by keys show in the sidebar too; a restored caret shows once.
258 if let path = session.path, selectedFile != path { selectedFile = path }
259 if let path = session.path, let caret = pendingCarets.removeValue(forKey: path) { session.reveal(caret) }
260 BufferRestore.save(session)
261 // Syncthing's conflict copies of the file.
262 let copies = session.syncConflictCopies().count
263 if copies > 0 { commands.show("\(copies) sync conflict \(copies == 1 ? "copy" : "copies") of this file; Resolve Sync Conflicts compares them.") }
264 }
265 .onChange(of: session.openPaths) { _, paths in
266 BufferRestore.save(session)
267 for path in commands.store.editors.keys where !paths.contains(path) { commands.store.releasePath(path) }
268 }
269 .onChange(of: editorSettings, initial: true) { _, settings in commands.editorSettings = settings }
270 .onAppear {
271 commands.externalHandler = runExternal
272 commands.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] }
273 if window == nil {
274 let model = WindowModel(session: session, pane: session.panes[0])
275 window = model
276 commands.store.windows.append(model)
277 }
278 }
279 .onChange(of: saveMode, initial: true) { _, mode in session.saveMode = mode }
280 .onChange(of: options, initial: true) { _, options in session.options = options }
281 .onChange(of: preset, initial: true) { loadKeymap() }
282 .sheet(isPresented: $showingImport) { EmacsImportView(workspace: workspace) }
283 .sheet(item: $panel) { panel in
284 switch panel {
285 case .columns(_, let view):
286 ColumnViewSheet(view: view) { offset in commands.editor?.reveal(offset) }
287 case .export(_, let source):
288 ExportSheet(source: source, inSubtree: exportSubtreeAvailable, target: exportTarget) { format, destination, open, subtree, bodyOnly in
289 export(format, to: destination, open: open, subtree: subtree, bodyOnly: bodyOnly)
290 }
291 case .conflict:
292 ConflictSheet(session: session)
293 case .syncCopies:
294 SyncConflictSheet(session: session) { commands.show($0) }
295 case .recovery:
296 RecoverySheet(session: session) { commands.show($0) }
297 }
298 }
299 .sheet(item: $blockEdit) { request in
300 BlockEditorView(edit: request.edit) { content in
301 blockEdit = nil
302 guard let content else { return }
303 commands.editor?.perform(ReplaceBlockLines(edit: request.edit, content: content))
304 }
305 }
306 .sheet(isPresented: $commands.showingPalette) {
307 PaletteView(commands: commands) { id in
308 commands.showingPalette = false
309 // After the sheet closes, so app commands can present their own.
310 DispatchQueue.main.async { perform(id) }
311 }
312 }
313 .onChange(of: session.conflict) { _, conflict in
314 if conflict != nil { commands.showingConflict = true }
315 }
316 .onChange(of: commands.showingConflict) { _, showing in
317 guard showing else { return }
318 commands.showingConflict = false
319 if session.conflict != nil { panel = .conflict(UUID()) }
320 }
321 .onChange(of: workspace.changedFile?.version) {
322 if let path = workspace.changedFile?.path { session.fileChanged(path) }
323 }
324 }
325
326 var body: some View {
327 main
328 .onChange(of: ClockMenuState(running: clock.running, history: clock.history), initial: true) { _, state in
329 if statusItem == nil { statusItem = ClockStatusItem { commands.run($0) } }
330 statusItem?.update(state.running, recent: state.history.map(\.title))
331 }
332 .onChange(of: globalCapture, initial: true) { _, enabled in
333 hotKey?.unregister()
334 hotKey = enabled ? GlobalHotKey { perform("app.capture") } : nil
335 }
336 .onChange(of: commands.runRequest?.serial) {
337 if let id = commands.runRequest?.id { perform(id) }
338 }
339 .onChange(of: ConfigSync.shared.problems, initial: true) { _, problems in
340 if let first = problems.first {
341 commands.show(first + (problems.count > 1 ? " (and \(problems.count - 1) more)" : ""))
342 }
343 }
344 .onChange(of: ConfigSync.shared.changedFile?.serial) {
345 if ConfigSync.shared.changedFile?.name == "keymap.toml" { loadKeymap() }
346 }
347 .onChange(of: commands.jumpRequest?.id) {
348 guard let request = commands.jumpRequest else { return }
349 if request.path != session.path {
350 session.open(request.path)
351 selectedFile = request.path
352 }
353 session.reveal(request.offset)
354 }
355 .onChange(of: commands.focusSearch) { _, focus in
356 if focus {
357 searchFocused = true
358 commands.focusSearch = false
359 }
360 }
361 .fileImporter(isPresented: $commands.showingFolderPicker, allowedContentTypes: [.folder]) { result in
362 guard case .success(let url) = result else { return }
363 Task {
364 do { try await workspace.addRoot(url) } catch { workspace.lastError = error.localizedDescription }
365 }
366 }
367 .sheet(isPresented: $commands.showingQuickOpen) {
368 QuickOpenView(workspace: workspace) { entry in
369 selectedFile = entry.path
370 commands.showingQuickOpen = false
371 }
372 }
373 .alert("orgstar", isPresented: errorShown) {
374 Button("OK") {
375 workspace.lastError = nil
376 session.lastError = nil
377 }
378 } message: {
379 Text(workspace.lastError ?? session.lastError ?? "")
380 }
381 .task(id: ReminderKey(
382 enabled: remindersEnabled, lead: reminderLead, subfolders: agendaSubfolders, files: workspace.files.count,
383 changed: workspace.changedFile?.version, edits: session.editVersion, hour: hour
384 )) {
385 await updateReminders()
386 }
387 .task {
388 while !Task.isCancelled {
389 try? await Task.sleep(for: .seconds(3600))
390 hour += 1
391 }
392 }
393 // `org-resolve-clocks-if-idle`, checked every minute while a clock runs.
394 .task(id: "\(clock.running?.start ?? "") \(clockIdleTime)") {
395 guard clock.running != nil, clockIdleTime > 0 else { return }
396 while !Task.isCancelled {
397 try? await Task.sleep(for: .seconds(60))
398 guard !Task.isCancelled, clock.running != nil, !clock.isResolving else { continue }
399 let idle = ClockIdle.seconds()
400 guard idle > Double(clockIdleTime * 60) else { continue }
401 NSApp.requestUserAttention(.informationalRequest)
402 report(await clock.resolveIdle(session, idleSince: Date().addingTimeInterval(-idle), ask: askClock))
403 }
404 }
405 .task {
406 DevelopmentHooks.scheduleSnapshot()
407 pendingCarets = BufferRestore.restore(session)
408 if let path = session.path, let caret = pendingCarets.removeValue(forKey: path) { session.reveal(caret) }
409 // Files handed over at launch open after the restored buffers, and show.
410 for path in AppDelegate.pendingOpens { session.open(path) }
411 AppDelegate.pendingOpens = []
412 for link in AppDelegate.pendingLinks + [DevelopmentHooks.urlToOpen].compactMap({ $0 }) { commands.handle(protocolURL: link) }
413 AppDelegate.pendingLinks = []
414 if let path = DevelopmentHooks.fileToOpen { selectedFile = path }
415 if let root = DevelopmentHooks.rootToAdd { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
416 if let commandList = DevelopmentHooks.commandToRun {
417 // The file opened above needs its editor first.
418 for _ in 0..<20 where DevelopmentHooks.fileToOpen != nil && commands.editor == nil { try? await Task.sleep(for: .milliseconds(100)) }
419 for command in commandList.split(separator: ",") { perform(String(command)) }
420 for answer in DevelopmentHooks.answers {
421 for _ in 0..<20 where commands.prompt == nil { try? await Task.sleep(for: .milliseconds(100)) }
422 commands.answer(answer)
423 }
424 }
425 if let id = DevelopmentHooks.windowToOpen {
426 if id == "settings" { openSettings() } else { openWindow(id: id) }
427 }
428 await workspace.refresh()
429 workspace.startWatching()
430 }
431 }
432
433 /// The selection, or the whole file without one, on the clipboard as HTML, RTF and plain
434 /// text, to paste formatted into mail and documents.
435 private func copyRichText() {
436 guard let path = session.path, let whole = session.document?.text, let editor = commands.editor else { return commands.show("No file is open") }
437 let defaults = Preferences.orgSettings.resolvingSetupFiles(in: whole, path: path, read: OrgSettings.readFile)
438 let selection = editor.context().selection.first { !$0.isEmpty }
439 let selected = selection.map { (whole as NSString).substring(with: NSRange($0)) }
440 let url = URL(fileURLWithPath: path)
441 let html = HTMLExport.page(
442 selected ?? whole, fallbackTitle: url.deletingPathExtension().lastPathComponent, settings: defaults, path: path, bodyOnly: selected != nil,
443 codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme)
444 )
445 do {
446 try RichTextExport.copy(html: html, directory: url.deletingLastPathComponent())
447 commands.show(selected == nil ? "Copied the file as rich text" : "Copied the selection as rich text")
448 } catch {
449 commands.show("\(error)")
450 }
451 }
452
453 /// Whether the caret is in a heading's subtree, which the export dialog can export alone.
454 private var exportSubtreeAvailable: Bool {
455 guard let text = session.document?.text, let caret = commands.editor?.context().caret else { return false }
456 return ExportScope.subtree(text, at: caret) != nil
457 }
458
459 /// Where an export goes by default: `#+EXPORT_FILE_NAME`, or the subtree's
460 /// `EXPORT_FILE_NAME`, else beside the file, with `ext`.
461 private func exportTarget(_ ext: String, subtree: Bool) -> URL {
462 let path = session.path ?? ""
463 let text = session.document?.text ?? ""
464 let caret = subtree ? commands.editor?.context().caret : nil
465 return ExportScope.output(for: URL(fileURLWithPath: path), name: ExportScope.fileName(text, subtreeAt: caret), extension: ext)
466 }
467
468 /// Writes the export where `#+EXPORT_FILE_NAME` says or beside the file, as Emacs's export
469 /// dispatcher does, or to `destination`, and opens it with `open`. `subtree` exports the
470 /// subtree at the caret alone; `bodyOnly` leaves out the title and page wrapper.
471 private func export(_ format: String, to destination: URL? = nil, open: Bool = false, subtree: Bool = false, bodyOnly: Bool = false) {
472 guard let path = session.path, var text = session.document?.text else {
473 commands.show("No file is open")
474 return
475 }
476 let url = URL(fileURLWithPath: path)
477 let base = url.deletingPathExtension()
478 let defaults = Preferences.orgSettings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
479 let open = open || format == "html-open"
480 let caret = commands.editor?.context().caret ?? 0
481 let whole = text
482 if subtree {
483 guard let narrowed = ExportScope.subtree(text, at: caret, settings: defaults) else { return commands.show("Not in a subtree") }
484 text = narrowed
485 }
486 switch format {
487 case "html", "html-open", "markdown":
488 let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
489 let target = destination ?? ExportScope.output(for: url, name: name, extension: format == "markdown" ? "md" : "html")
490 let content = format == "markdown"
491 ? MarkdownExport.document(text, settings: defaults, path: path, bodyOnly: bodyOnly)
492 : HTMLExport.page(
493 text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path, bodyOnly: bodyOnly,
494 codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme)
495 )
496 do {
497 try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
498 try content.write(to: target, atomically: true, encoding: .utf8)
499 commands.show("Exported to \(target.lastPathComponent)")
500 if open { NSWorkspace.shared.open(target) }
501 } catch {
502 commands.show("Can't write \(target.lastPathComponent): \(error.localizedDescription)")
503 }
504 case "print-pdf", "docx", "rtf", "plain-text":
505 let ext = ["print-pdf": "pdf", "plain-text": "txt"][format] ?? format
506 let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
507 let target = destination ?? ExportScope.output(for: url, name: name, extension: ext)
508 let html = HTMLExport.page(
509 text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path,
510 codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme)
511 )
512 let directory = url.deletingLastPathComponent()
513 if format == "print-pdf" { commands.show("Exporting to PDF…") }
514 Task {
515 do {
516 let data: Data
517 switch format {
518 case "print-pdf": data = try await PDFExport.pdf(html: html, directory: directory)
519 case "docx": data = try RichTextExport.docx(RichTextExport.attributed(html: html, directory: directory))
520 case "rtf": data = try RichTextExport.rtf(RichTextExport.attributed(html: html, directory: directory))
521 default: data = Data(RichTextExport.plain(try RichTextExport.attributed(html: html, directory: directory)).utf8)
522 }
523 try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
524 try data.write(to: target, options: .atomic)
525 commands.show("Exported to \(target.lastPathComponent)")
526 if open { NSWorkspace.shared.open(target) }
527 } catch {
528 commands.show("Can't export \(target.lastPathComponent): \(error)")
529 }
530 }
531 default:
532 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"]
533 guard let function = functions[format] else { return }
534 commands.show("Exporting with Emacs…")
535 commands.runInEmacs {
536 do {
537 // Emacs narrows to the subtree and reads EXPORT_FILE_NAME itself.
538 let point = subtree ? (whole as NSString).substring(to: min(caret, (whole as NSString).length)).unicodeScalars.count + 1 : nil
539 var written = URL(fileURLWithPath: try await EmacsRunner.export(
540 text: whole, path: path, function: function, subtree: point, bodyOnly: bodyOnly
541 ))
542 if let destination, destination.standardizedFileURL != written.standardizedFileURL {
543 try? FileManager.default.removeItem(at: destination)
544 try FileManager.default.moveItem(at: written, to: destination)
545 written = destination
546 }
547 commands.show("Exported to \(written.lastPathComponent)")
548 if open { NSWorkspace.shared.open(written) }
549 } catch is CancellationError {
550 commands.show("Export canceled")
551 } catch {
552 commands.show("\(error)")
553 }
554 }
555 }
556 }
557
558 /// Work a command hands to the platform: tables recalculated in Emacs.
559 private func runExternal(_ request: ExternalRequest) {
560 switch request {
561 case .openLink(let link):
562 if let message = LinkOpener.open(link, session: session, workspace: workspace) { commands.show(message) }
563 case .tangle(let scope):
564 commands.show(session.tangle(scope))
565 case .agenda(let start, let days):
566 commands.agendaRequest = (start, days)
567 openWindow(id: "agenda")
568 case .editBlock(let edit):
569 blockEdit = BlockEditRequest(edit: edit)
570 case .columnView(let view):
571 panel = .columns(UUID(), view)
572 case .emacsTable(let table, let point, let form, let reason, let lisp):
573 let run = {
574 commands.show("Recalculating in Emacs (\(reason))…")
575 commands.runInEmacs { commands.show(await session.recalculateInEmacs(table: table, point: point, form: form)) }
576 }
577 guard lisp, let path = session.path, let text = session.document?.text else { return run() }
578 let content = (text as NSString).substring(with: NSRange(location: table.lowerBound, length: min((text as NSString).length, table.upperBound + 2000) - table.lowerBound))
579 if trust.isTrusted(path: path, content: content) { return run() }
580 commands.ask(Prompt(key: "confirm", message: "This table's formulas run Lisp. Run them? (yes, no, always)", choices: ["yes", "no", "always"])) { answer in
581 switch answer {
582 case "always":
583 trust.trust(path: path, content: content)
584 run()
585 case "yes": run()
586 default: commands.show("Not recalculated")
587 }
588 }
589 case .babel(let job):
590 let run = {
591 commands.show("Running \(job.language) block… (⌘. to cancel)")
592 session.startBabel(job) { commands.show($0) }
593 }
594 guard let path = session.path else { return }
595 if !job.alwaysAsk, trust.isTrusted(path: path, content: job.blockText) { return run() }
596 let choices = job.alwaysAsk ? ["yes", "no"] : ["yes", "no", "always"]
597 commands.ask(Prompt(key: "confirm", message: "Run this \(job.language) block? (\(choices.joined(separator: ", ")))", choices: choices)) { answer in
598 switch answer {
599 case "always":
600 trust.trust(path: path, content: job.blockText)
601 run()
602 case "yes": run()
603 default: commands.show("Not run")
604 }
605 }
606 }
607 }
608
609 private struct ReminderKey: Hashable {
610 var enabled: Bool
611 var lead: Int
612 var subfolders: Bool
613 var files: Int
614 var changed: Int?
615 var edits: Int
616 var hour: Int
617 }
618
619 /// Sets the notifications for the next week's timed entries, once edits pause.
620 private func updateReminders() async {
621 guard let scheduler else { return }
622 guard remindersEnabled else {
623 await scheduler.clear()
624 return
625 }
626 try? await Task.sleep(for: .seconds(2))
627 guard !Task.isCancelled, !workspace.files.isEmpty else { return }
628 let agenda = reminderAgenda ?? AgendaModel(workspace: workspace)
629 reminderAgenda = agenda
630 agenda.includeSubfolders = agendaSubfolders
631 let open = session.openTexts
632 let reminders = await agenda.reminders(open: open, lead: reminderLead)
633 guard !Task.isCancelled else { return }
634 await scheduler.reconcile(reminders)
635 }
636
637 private func loadKeymap() {
638 let loaded = KeymapLoader.load(preset, commands: Set(EditorCommands.all.map(\.id)))
639 keymap = loaded.keymap
640 commands.keymap = loaded.keymap
641 commands.modal = preset.isModal
642 if let first = loaded.problems.first {
643 let more = loaded.problems.count > 1 ? " (and \(loaded.problems.count - 1) more)" : ""
644 commands.show("keymap.toml: \(first)\(more)")
645 }
646 }
647
648 /// `SPC b b`: open buffers, most recent first, by name (with the folder when names repeat).
649 private func switchBuffer() {
650 let paths = session.recentPaths.dropFirst() + session.recentPaths.prefix(1)
651 let labels = paths.map(session.bufferName)
652 guard !labels.isEmpty else { return commands.show("No buffers are open") }
653 commands.ask(Prompt(key: "buffer", message: "Switch to buffer:", choices: labels)) { answer in
654 guard let answer, let index = labels.firstIndex(of: answer) else { return }
655 session.open(Array(paths)[index])
656 }
657 }
658
659 /// Runs a command from a key, the palette or the Org menu.
660 private func perform(_ id: String) {
661 let orgOnly = ["app.refile", "app.archive", "app.clock.in", "app.clock.default", "app.copy-rich-text"].contains(id) || id.hasPrefix("app.export.") || id.hasPrefix("org.")
662 if orgOnly, !session.isOrg {
663 commands.show("Not an org file")
664 return
665 }
666 switch id {
667 case "app.save":
668 if !session.save(), session.conflict != nil { commands.showingConflict = true }
669 case "app.quit": NSApp.terminate(nil)
670 case "app.save-all":
671 if !session.saveAll(), session.conflict != nil { commands.showingConflict = true }
672 case "app.buffer.switch": switchBuffer()
673 case "app.buffer.next": session.cycle(1)
674 case "app.buffer.previous": session.cycle(-1)
675 case "app.buffer.last": session.showPrevious()
676 case "app.buffer.kill":
677 guard let path = session.path else {
678 NSApp.keyWindow?.performClose(nil)
679 return
680 }
681 if UnsavedChanges.resolve(session) { session.kill(path) }
682 case "app.buffer.kill-others":
683 let others = session.openPaths.filter { $0 != session.path }
684 if UnsavedChanges.resolve(session, paths: others) { others.forEach(session.kill) }
685 case "app.buffer.kill-all":
686 let all = session.openPaths
687 if UnsavedChanges.resolve(session, paths: all) { all.forEach(session.kill) }
688 case "app.toggle-tab-bar": showTabBar.toggle()
689 case "app.split-below": paneWindow?.split(.vertical)
690 case "app.split-right": paneWindow?.split(.horizontal)
691 case "app.pane-close":
692 guard let window = paneWindow, window.paneCount > 1 else { return commands.show("Attempt to delete the only pane") }
693 commands.store.releasePane(window.focused)
694 window.close(window.focused)
695 focusPane(window)
696 case "app.pane-only":
697 guard let window = paneWindow else { return }
698 for id in window.layout.panes where id != window.focused { commands.store.releasePane(id) }
699 window.closeOthers()
700 focusPane(window)
701 case "app.pane-next":
702 guard let window = paneWindow else { return }
703 window.focusNext()
704 focusPane(window)
705 case "app.window-new": openWindow(id: "editor")
706 case "app.babel.cancel":
707 if session.isRunningBabel {
708 session.cancelBabel()
709 } else if let task = commands.emacsTask {
710 task.cancel()
711 } else {
712 commands.show("Nothing is running")
713 }
714 case "app.toggle-outline": toggleOutline()
715 case "app.toggle-backlinks": backlinksShown.toggle()
716 case "app.toggle-inspector": inspectorShown.toggle()
717 case "app.toggle-markup": showMarkup.toggle()
718 case "app.toggle-line-numbers": showLineNumbers.toggle()
719 case "app.import-emacs": showingImport = true
720 case "app.edit-config": commands.jump(path: UserConfig.configFile.path, offset: 0)
721 case "app.quick-open": commands.showingQuickOpen = true
722 case "app.palette": commands.showingPalette = true
723 case "app.search": commands.focusSearch = true
724 case "app.reload-keymap":
725 loadKeymap()
726 commands.show("Keymap reloaded")
727 case "app.refile":
728 let targets = workspace.refileTargets(openPath: session.path, document: session.document)
729 commands.ask(Prompt(key: "refile", message: "Refile to:", choices: targets.map(\.label))) { answer in
730 guard let answer, let target = targets.first(where: { $0.label == answer }) else { return }
731 if let message = session.refile(to: target) { commands.show(message) }
732 }
733 case "app.archive":
734 if let message = session.archive() { commands.show(message) }
735 case "app.table-import":
736 // `org-table-import`: a TSV, CSV or space-separated file becomes a table at point.
737 guard let editor = commands.editor else { return commands.show("No file is open") }
738 let panel = NSOpenPanel()
739 panel.allowedContentTypes = [.commaSeparatedText, .tabSeparatedText, .plainText]
740 guard panel.runModal() == .OK, let url = panel.url else { return }
741 guard let contents = try? String(contentsOf: url, encoding: .utf8) else { return commands.show("Can't read \(url.lastPathComponent)") }
742 editor.perform(ImportTable(contents: contents))
743 case "app.table-export":
744 // `org-table-export`: CSV for a .csv name, else TSV.
745 guard let editor = commands.editor else { return commands.show("No file is open") }
746 let context = editor.context()
747 guard ImportTable.exportText(context.text, at: context.caret, path: "") != nil else { return commands.show("No table at point") }
748 let panel = NSSavePanel()
749 panel.nameFieldStringValue = "table.csv"
750 guard panel.runModal() == .OK, let url = panel.url,
751 let text = ImportTable.exportText(context.text, at: context.caret, path: url.path) else { return }
752 do {
753 try text.write(to: url, atomically: true, encoding: .utf8)
754 commands.show("Export done.")
755 } catch {
756 commands.show("File not written: \(error.localizedDescription)")
757 }
758 case "org.subtree.paste":
759 guard let text = NSPasteboard.general.string(forType: .string) else { return commands.show("The clipboard is empty") }
760 commands.editor?.perform(PasteSubtree(text: text))
761 case "org.link.insert":
762 commands.editor?.perform(InsertLink(stored: commands.storedLinks, file: session.path))
763 case "org.link.store":
764 guard let editor = commands.editor, let path = session.path else { return commands.show("No method for storing a link from this buffer") }
765 commands.storeLink(Links.store(in: editor.context(), path: Links.abbreviate(path, home: NSHomeDirectory())))
766 case "org.id.store-link":
767 guard let editor = commands.editor, let path = session.path else { return }
768 if case .commit = editor.perform(CreateID()),
769 let link = Links.storeID(in: editor.context(), fileName: (path as NSString).lastPathComponent) {
770 commands.storeLink(link)
771 }
772 case "app.agenda":
773 openWindow(id: "agenda")
774 case "app.clock.in":
775 clockIn(.caret)
776 case "app.clock.in-recent":
777 clockIn(.select)
778 case "app.clock.in-last":
779 clockIn(.last)
780 case let id where id.hasPrefix("app.clock.history."):
781 if let index = Int(id.dropFirst("app.clock.history.".count)), index < clock.history.count { clockIn(.task(clock.history[index])) }
782 case "app.clock.out":
783 commands.show(clock.clockOut(session))
784 case "app.clock.cancel":
785 commands.show(clock.clockOut(session, cancel: true))
786 case "app.clock.goto":
787 let found = clock.goto(session)
788 if let location = found.location { commands.jump(path: location.path, offset: location.offset) }
789 if let message = found.message { commands.show(message) }
790 case "app.clock.goto-recent":
791 Task {
792 let found = await clock.gotoRecent(session, ask: askClock)
793 if let location = found.location { commands.jump(path: location.path, offset: location.offset) }
794 if let message = found.message { commands.show(message) }
795 }
796 case "app.clock.default":
797 commands.show(clock.markDefault(session))
798 case "app.clock.resolve":
799 Task { report(await clock.resolveOpenClocks(session, paths: orgFiles, ask: askClock)) }
800 case "app.clock.report":
801 openWindow(id: "clock-report")
802 case "app.board":
803 openWindow(id: "board")
804 case "app.capture":
805 NSApp.activate()
806 openWindow(id: "capture")
807 case "app.revert":
808 // `:e`: the file as it is on disk; unsaved changes go to recovery.
809 guard session.path != nil else { return commands.show("No file is open") }
810 session.useDiskVersion()
811 commands.show("Reverted to the file on disk")
812 case "app.sync-conflicts":
813 guard session.path != nil else { return commands.show("No file is open") }
814 panel = .syncCopies(UUID())
815 case "app.recovery":
816 guard session.path != nil else { return commands.show("No file is open") }
817 panel = .recovery(UUID())
818 case "app.copy-rich-text":
819 copyRichText()
820 case "app.export-dialog":
821 guard let path = session.path else { return commands.show("No file is open") }
822 panel = .export(UUID(), URL(fileURLWithPath: path))
823 case let id where id.hasPrefix("app.export."):
824 export(String(id.dropFirst("app.export.".count)))
825 default:
826 if let editor = commands.editor { editor.run(id) } else { commands.show("No file is open") }
827 }
828 }
829
830 private var askClock: ClockModel.Ask { commands.askClock }
831
832 /// The files `org-resolve-clocks` looks through: the workspace's org files.
833 private var orgFiles: [String] { workspace.files.filter { $0.kind == .org }.map(\.path) }
834
835 private func clockIn(_ target: ClockModel.Target) {
836 Task { report(await clock.clockIn(session, target: target, paths: orgFiles, ask: askClock)) }
837 }
838
839 /// The last message of a clock command, and the clock to show for `j`.
840 private func report(_ outcome: ClockModel.Outcome) {
841 if let jump = outcome.jump { commands.jump(path: jump.path, offset: jump.offset) }
842 if let message = outcome.messages.last(where: { !$0.isEmpty }) { commands.show(message) }
843 }
844
845 private var errorShown: Binding<Bool> {
846 Binding(get: { workspace.lastError != nil || session.lastError != nil }, set: { _ in })
847 }
848}