Sources/Orgstar/ContentView.swift
1412 lines · 77990 bytes
1import AppKit
2import OrgApp
3import OrgCore
4import OrgEditorAppKit
5import OrgPresentation
6import OrgWorkspace
7import OrgIndex
8#if !APPSTORE
9import OrgPrograms
10#endif
11import SwiftUI
12import UniformTypeIdentifiers
13import WidgetKit
14
15struct ContentView: View {
16 let workspace: WorkspaceModel
17 let session: DocumentSession
18 @Bindable var commands: AppCommands
19 let scheduler: ReminderScheduler?
20 let clock: ClockModel
21 @AppStorage("reminders") private var remindersEnabled = true
22 @AppStorage("reminderLead") private var reminderLead = 12
23 @AppStorage("clockIdleTime") private var clockIdleTime = 0
24 @AppStorage("agendaSubfolders") private var agendaSubfolders = false
25 @State private var reminderAgenda: AgendaModel?
26 @State private var widgetAgenda: AgendaModel?
27 @State private var trust = TrustStore()
28 @State private var hotKey: GlobalHotKey?
29 @State private var statusItem: ClockStatusItem?
30 @AppStorage("globalCapture") private var globalCapture = true
31 @State private var hour = 0
32 @AppStorage("saveMode") private var saveMode = SaveMode.automatic
33 @AppStorage("keymap") private var preset = KeymapPreset.emacs
34 @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
35 @State private var keymap = KeymapPreset.emacs.keymap
36 @AppStorage("tagsColumn") private var tagsColumn = -77
37 @AppStorage("headingAfterSubtree") private var headingAfterSubtree = false
38 /// The welcome sheet has been shown once; it comes back only through the empty state.
39 @AppStorage("welcomeShown") private var welcomeShown = false
40 @AppStorage("splitLine") private var splitLine = false
41 @AppStorage("alphabeticalLists") private var alphabeticalLists = true
42 @AppStorage("fillColumn") private var fillColumn = 80
43 @AppStorage("hiddenMarkers") private var hiddenMarkers = true
44 @AppStorage("prettyEntities") private var prettyEntities = true
45 @AppStorage("logDone") private var logDone = "nil"
46 @AppStorage("logIntoDrawer") private var logIntoDrawer = ""
47 @AppStorage("logReschedule") private var logReschedule = "nil"
48 @AppStorage("logRedeadline") private var logRedeadline = "nil"
49 @AppStorage("useSpeedCommands") private var useSpeedCommands = false
50 @AppStorage("startupWithInlineImages") private var startupWithInlineImages = false
51 @AppStorage("startupIndented") private var startupIndented = true
52 @AppStorage("hideLeadingStars") private var hideLeadingStars = false
53 @AppStorage("startupAlignAllTables") private var startupAlignAllTables = false
54 @AppStorage("startupTruncated") private var startupTruncated = false
55 @AppStorage("spellCheck") private var spellCheck = false
56 @AppStorage("electricPair") private var electricPair = true
57 @AppStorage("hideDrawerStartup") private var hideDrawerStartup = true
58 @AppStorage("hideBlockStartup") private var hideBlockStartup = false
59 @AppStorage("enforceTodoDependencies") private var enforceTodoDependencies = false
60 @AppStorage("enforceTodoCheckboxDependencies") private var enforceTodoCheckboxDependencies = false
61
62 /// Bumped when user defaults change, so settings only config.toml has reach `options`.
63 @State private var defaultsChanges = 0
64 private var options: EditingOptions {
65 _ = defaultsChanges
66 var options = Preferences.options(
67 tagsColumn: tagsColumn, headingAfterSubtree: headingAfterSubtree, splitLine: splitLine, alphabeticalLists: alphabeticalLists,
68 fillColumn: fillColumn, hiddenMarkers: hiddenMarkers, prettyEntities: prettyEntities, logDone: logDone, logIntoDrawer: logIntoDrawer,
69 hideDrawerStartup: hideDrawerStartup, hideBlockStartup: hideBlockStartup, logReschedule: logReschedule, logRedeadline: logRedeadline,
70 useSpeedCommands: useSpeedCommands, startupWithInlineImages: startupWithInlineImages,
71 startupIndented: startupIndented, hideLeadingStars: hideLeadingStars, startupAlignAllTables: startupAlignAllTables,
72 startupTruncated: startupTruncated, spellCheck: spellCheck, electricPair: electricPair,
73 enforceTodoDependencies: enforceTodoDependencies, enforceTodoCheckboxDependencies: enforceTodoCheckboxDependencies
74 )
75 // The agenda files, for clock tables over `agenda` scopes.
76 options.agendaFiles = workspace.agendaFilePaths()
77 options.denoteDirectories = DenoteNote.directories(roots: workspace.rootPaths)
78 options.denoteSequenceScheme = OrgPreferences.denoteSequenceScheme()
79 options.timer = TimerModel.shared.timer
80 return options
81 }
82 /// A block being edited apart (`org-edit-special`).
83 @State private var blockEdit: BlockEditRequest?
84 /// A sheet a command opened: column view or the export dialog.
85 @State private var panel: Panel?
86
87 @State private var selectedFile: String?
88 /// A file that isn't text, shown as a preview instead of the open document.
89 @State private var previewPath: String?
90 @AppStorage("outlineShown") private var orgOutlineShown = true
91 @AppStorage("outlineWidth") private var outlineWidth = 220.0
92 @AppStorage("backlinksShown") private var backlinksShown = true
93 @AppStorage("inspectorShown") private var inspectorShown = false
94 @AppStorage("showMarkup") private var showMarkup = false
95 @AppStorage("showLineNumbers") private var showLineNumbers = false
96 @AppStorage("lineNumbersType") private var lineNumbersType = "t"
97 @AppStorage("showHiddenFiles") private var showHiddenFiles = true
98 @AppStorage("ignoredFolders") private var ignoredFolders = ScanRules.defaultIgnoredFolders.sorted().joined(separator: " ")
99 @AppStorage("themeFont") private var themeFont = ""
100 @AppStorage("themeBodyFont") private var themeBodyFont = ""
101 @AppStorage("themeFontSize") private var themeFontSize = 13
102 @AppStorage("themeLineSpacing") private var themeLineSpacing = 2
103 @AppStorage("themeTextWidth") private var themeTextWidth = 0
104 @AppStorage("themeHeadingStep") private var themeHeadingStep = 1
105
106 /// The theme's colors from config.toml with the type settings.
107 private var theme: ThemeSpec {
108 var spec = ConfigSync.shared.theme
109 spec.font = themeFont
110 spec.bodyFont = themeBodyFont
111 spec.fontSize = themeFontSize
112 spec.lineSpacing = themeLineSpacing
113 spec.textWidth = themeTextWidth
114 spec.headingSizeStep = themeHeadingStep
115 return spec
116 }
117 /// The outline for a file that isn't org, off until asked for.
118 @State private var plainOutlineShown = false
119 @State private var showingImport = false
120 @AppStorage("showTabBar") private var showTabBar = false
121 /// This window's panes.
122 @State private var window: WindowModel?
123
124 private var editorSettings: EditorSettings {
125 EditorSettings(keymap: keymap, modal: preset.isModal, optionAsMeta: OptionAsMeta(rawValue: optionAsMeta), options: options, showMarkup: showMarkup, showLineNumbers: showLineNumbers,
126 lineNumbersType: LineNumbersType(rawValue: lineNumbersType) ?? .absolute, theme: theme)
127 }
128
129 /// The pane that had the focus when a sheet opened, to act on when it closes.
130 @State private var sheetTarget: EditorPane?
131
132 /// Puts the focus back on the pane a sheet was opened from.
133 private func restoreSheetTarget() {
134 guard let target = sheetTarget, session.panes.contains(where: { $0 === target }) else { return }
135 sheetTarget = nil
136 session.focused = target
137 if let window = commands.store.window(of: target.id) { window.focused = target.id }
138 if let path = target.path, let textView = commands.store.textView(for: target.id, path: path) {
139 textView.window?.makeFirstResponder(textView)
140 commands.editor = commands.store.editor(for: path)
141 }
142 }
143
144 /// The window holding the focused pane: this one, or an editor window.
145 private var paneWindow: WindowModel? {
146 commands.store.window(of: session.focused.id) ?? window
147 }
148
149 /// Gives the focused pane's text view the keyboard, after a pane command moved the focus.
150 private func focusPane(_ window: WindowModel) {
151 window.activate(commands)
152 }
153 /// Carets of restored buffers, shown when each first shows.
154 @State private var pendingCarets: [String: Int] = [:]
155 @State private var query = ""
156 @FocusState private var searchFocused: Bool
157 @Environment(\.openWindow) private var openWindow
158 @Environment(\.openSettings) private var openSettings
159
160 /// Whether the outline pane shows: remembered for org files, hidden by default for
161 /// other files, and always shown while search results are up.
162 private var outlineShown: Bool {
163 !query.isEmpty || (previewPath == nil && (session.isOrg ? orgOutlineShown : plainOutlineShown))
164 }
165
166 private func toggleOutline() {
167 if session.isOrg { orgOutlineShown.toggle() } else { plainOutlineShown.toggle() }
168 }
169
170 @ViewBuilder
171 private var detail: some View {
172 if let previewPath {
173 FilePreview(path: previewPath)
174 } else if !session.openPaths.isEmpty, let window {
175 PaneLayoutView(layout: window.layout, window: window) { pane in
176 PaneCell(pane: pane, window: window, session: session, commands: commands, showTabBar: showTabBar, onAppCommand: perform)
177 }
178 .safeAreaInset(edge: .bottom, spacing: 0) {
179 VStack(spacing: 0) {
180 ModeLine(session: session, commands: commands, clock: clock, perform: perform)
181 EchoArea(commands: commands)
182 }
183 }
184 } else {
185 ContentUnavailableView {
186 Label(noFolders ? "Add a folder of org files" : "Choose a file", systemImage: "doc.text")
187 } description: {
188 Text(noFolders ? "File ▸ Add Folder… (⇧⌘O)" : "Or press ⌘P to open one by name.")
189 } actions: {
190 if noFolders { Button("Get Started…") { commands.showingWelcome = true } }
191 }
192 }
193 }
194
195 /// No folder to show: in the App Store build, also when none of them resolves, so the
196 /// welcome sheet can ask for them again.
197 private var noFolders: Bool {
198 #if APPSTORE
199 workspace.rootPaths.isEmpty
200 #else
201 workspace.roots.isEmpty
202 #endif
203 }
204
205 @ToolbarContentBuilder
206 private var toolbarItems: some ToolbarContent {
207 ToolbarItem(placement: .navigation) {
208 Button(outlineShown ? "Hide Outline" : "Show Outline", systemImage: "list.bullet.indent") { toggleOutline() }
209 .help(outlineShown ? "Hide the outline (⌥⌘O)" : "Show the outline (⌥⌘O)")
210 .disabled(!query.isEmpty || previewPath != nil || session.path == nil)
211 }
212 if workspace.isIndexing {
213 ToolbarItem { ProgressView().controlSize(.small) }
214 }
215 if let running = clock.running {
216 ToolbarItem {
217 Menu {
218 Button("Clock Out") { perform("app.clock.out") }
219 Button("Cancel Clock") { perform("app.clock.cancel") }
220 Button("Go to Clocked Entry") { perform("app.clock.goto") }
221 Divider()
222 Button("Clock In to Recent Entry…") { perform("app.clock.in-recent") }
223 Button("Go to Recent Clocked Entry…") { perform("app.clock.goto-recent") }
224 RecentClocks(clock: clock) { perform($0) }
225 } label: {
226 TimelineView(.periodic(from: .now, by: 30)) { context in
227 Text("⏱ \(running.heading) \(clockElapsed(running, now: context.date))").lineLimit(1)
228 }
229 }
230 .help("Clocked in since \(running.startedAt.formatted(date: .omitted, time: .shortened))")
231 }
232 }
233 if session.conflict != nil {
234 ToolbarItem {
235 Button("Conflict", systemImage: "exclamationmark.triangle") { commands.showingConflict = true }
236 .help("The file changed on disk, and the changes conflict with yours")
237 }
238 }
239 }
240
241 private var main: some View {
242 NavigationSplitView {
243 Sidebar(workspace: workspace, session: session, selection: $selectedFile) { commands.showingFolderPicker = true }
244 .navigationSplitViewColumnWidth(min: 200, ideal: 260)
245 } detail: {
246 HStack(spacing: 0) {
247 if outlineShown {
248 Group {
249 if query.isEmpty {
250 VStack(spacing: 0) {
251 OutlineColumn(session: session)
252 if backlinksShown, session.isOrg {
253 Divider()
254 BacklinksPane(workspace: workspace, session: session, commands: commands) { location in
255 selectedFile = location.path
256 session.show(location)
257 }
258 .frame(height: 200)
259 }
260 }
261 } else {
262 SearchResults(results: workspace.search(query, overlay: workspace.overlay(session.openDocuments))) { location in
263 selectedFile = location.path
264 session.show(location)
265 }
266 }
267 }
268 .frame(width: CGFloat(outlineWidth))
269 PaneDivider(width: $outlineWidth, range: 160...400)
270 }
271 detail
272 .frame(maxWidth: .infinity)
273 .inspector(isPresented: $inspectorShown) {
274 InspectorPane(session: session, commands: commands)
275 .inspectorColumnWidth(min: 240, ideal: 340, max: 600)
276 }
277 }
278 }
279 .navigationTitle(previewPath.map { ($0 as NSString).lastPathComponent } ?? session.path.map(session.bufferName) ?? "orgstar")
280 .navigationSubtitle(session.isReadOnly ? "Read-only: not UTF-8" : "")
281 .searchable(text: $query, placement: .toolbar, prompt: "Search notes")
282 .searchFocused($searchFocused)
283 .toolbar { toolbarItems }
284 .onChange(of: session.path) { plainOutlineShown = false }
285 .onChange(of: ScanRules(hiddenFiles: showHiddenFiles, ignoredFolders: Set(ignoredFolders.split(separator: " ").map(String.init))), initial: true) { _, rules in
286 workspace.scanRules = rules
287 }
288 .onChange(of: selectedFile) { old, path in
289 guard let path else { return }
290 if !DocumentSession.isOrgPath(path), !FileTypes.isText(path) {
291 previewPath = path
292 return
293 }
294 previewPath = nil
295 guard path != session.path else { return }
296 session.open(path)
297 }
298 .onChange(of: session.path) {
299 // Buffers switched by keys show in the sidebar too; a restored caret shows once.
300 if let path = session.path, selectedFile != path { selectedFile = path }
301 if let path = session.path, let caret = pendingCarets.removeValue(forKey: path) { session.reveal(caret) }
302 saveBuffers()
303 // Syncthing's conflict copies of the file.
304 let copies = session.syncConflictCopies().count
305 if copies > 0 { commands.show("\(copies) sync conflict \(copies == 1 ? "copy" : "copies") of this file; Resolve Sync Conflicts compares them.") }
306 }
307 .onChange(of: session.openPaths) { _, paths in
308 saveBuffers()
309 for path in commands.store.editors.keys where !paths.contains(path) { commands.store.releasePath(path) }
310 }
311 .onChange(of: editorSettings, initial: true) { _, settings in commands.editorSettings = settings }
312 .onAppear {
313 commands.externalHandler = runExternal
314 commands.filesHandler = { attachActions.drop($0) }
315 commands.imageHandler = { attachActions.yankImage($0, ext: $1) }
316 #if APPSTORE
317 commands.reach = { [workspace] in GrantAccess.reach($0, workspace: workspace) }
318 #endif
319 // `org-clock-out-when-done`, and the notification when the Effort runs out.
320 clock.notifications = SystemReminderCenter.isAvailable ? SystemReminderCenter() : nil
321 session.textChanged = { [weak session, weak clock, weak commands] path in
322 guard let session, let clock, let message = clock.textChanged(path, session) else { return }
323 commands?.show(message)
324 }
325 clock.remindAtEffort(session)
326 commands.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] }
327 commands.mainWindowOpen = true
328 if noFolders, !welcomeShown {
329 welcomeShown = true
330 commands.showingWelcome = true
331 }
332 if let stale = window { commands.store.windows.removeAll { $0 === stale } }
333 // The session's first pane the first time; a new one showing the focused buffer
334 // when the window opens again.
335 let pane: EditorPane
336 if commands.store.window(of: session.panes[0].id) == nil, window == nil {
337 pane = session.panes[0]
338 } else {
339 pane = session.makePane()
340 if let path = session.focused.path { session.open(path, in: pane) }
341 }
342 let model = WindowModel(session: session, pane: pane)
343 window = model
344 commands.store.windows.insert(model, at: 0)
345 model.focus(pane.id)
346 }
347 .onDisappear {
348 commands.mainWindowOpen = false
349 guard let model = window else { return }
350 for id in model.layout.panes { commands.store.releasePane(id) }
351 model.closeAll()
352 commands.store.windows.removeAll { $0 === model }
353 commands.editor = nil
354 }
355 .onChange(of: saveMode, initial: true) { _, mode in session.saveMode = mode }
356 .onChange(of: options, initial: true) { _, options in session.options = options }
357 .onAppear { TimerModel.shared.onDone = { [commands] in commands.show($0) } }
358 .onReceive(NotificationCenter.default.publisher(for: UserDefaults.didChangeNotification)) { _ in defaultsChanges += 1 }
359 .onChange(of: preset, initial: true) { loadKeymap() }
360 .sheet(isPresented: $showingImport) { EmacsImportView(workspace: workspace) }
361 .sheet(item: $panel) { panel in panelView(panel) }
362 .sheet(item: Bindable(ProAccess.shared).paywall) { feature in
363 #if APPSTORE
364 StorePaywallSheet(feature: feature)
365 #else
366 ProPaywallSheet(feature: feature)
367 #endif
368 }
369 .sheet(item: $blockEdit) { request in
370 BlockEditorView(edit: request.edit) { content in
371 blockEdit = nil
372 guard let content else { return }
373 commands.editor?.perform(ReplaceBlockLines(edit: request.edit, content: content))
374 }
375 }
376 .sheet(isPresented: $commands.showingWelcome) {
377 WelcomeView(workspace: workspace, chooseFolder: {
378 // After the sheet closes, so the picker can present.
379 DispatchQueue.main.async { commands.showingFolderPicker = true }
380 }, open: { selectedFile = $0 })
381 }
382 .sheet(isPresented: $commands.showingPalette) {
383 PaletteView(commands: commands) { id in
384 commands.showingPalette = false
385 // After the sheet closes, so app commands can present their own, and in the
386 // pane that had the focus when it opened: closing a sheet makes this window key.
387 DispatchQueue.main.async {
388 restoreSheetTarget()
389 perform(id)
390 }
391 }
392 }
393 .onChange(of: commands.showingPalette) { _, showing in if showing { sheetTarget = session.focused } }
394 .onChange(of: commands.showingQuickOpen) { _, showing in if showing { sheetTarget = session.focused } }
395 .onChange(of: session.conflict) { _, conflict in
396 if conflict != nil { commands.showingConflict = true }
397 }
398 .onChange(of: commands.showingConflict) { _, showing in
399 guard showing else { return }
400 commands.showingConflict = false
401 if session.conflict != nil { panel = .conflict(UUID()) }
402 }
403 .onChange(of: workspace.changedFile?.version) { fileChangedOnDisk() }
404 }
405
406 /// A column view edit at the heading starting at `start` in the open file.
407 private func runInColumnView(_ command: any OrgCommand, _ start: Int, _ answers: [String: String]) -> CommandStep {
408 guard let path = session.path else { return .failed("No file is open") }
409 return session.perform(command, path: path, at: start, expect: nil, answers: answers)
410 }
411
412 /// An open file takes in what changed on disk, and a clock started or stopped in Emacs
413 /// becomes the one shown.
414 private func fileChangedOnDisk() {
415 guard let path = workspace.changedFile?.path else { return }
416 session.fileChanged(path)
417 if path.hasSuffix(".org") { syncClock(paths: [path]) }
418 }
419
420 /// Open clocks in `paths`: at launch and as folders load, the agenda files.
421 private func syncClock(paths: [String]) {
422 guard !workspace.files.isEmpty, let message = clock.sync(session, paths: paths) else { return }
423 commands.show(message)
424 }
425
426 var body: some View {
427 main
428 .task(id: workspace.files.count) { syncClock(paths: workspace.agendaFilePaths()) }
429 .onChange(of: ClockMenuState(running: clock.running, history: clock.history), initial: true) { _, state in
430 if statusItem == nil { statusItem = ClockStatusItem { commands.run($0) } }
431 statusItem?.update(state.running, recent: state.history.map(\.title))
432 }
433 .onChange(of: globalCapture, initial: true) { _, enabled in
434 hotKey?.unregister()
435 hotKey = enabled ? GlobalHotKey { perform("app.capture") } : nil
436 }
437 .onChange(of: commands.runRequest?.serial, initial: true) {
438 if let id = commands.runRequest?.id { perform(id) }
439 }
440 .onChange(of: ConfigSync.shared.problems, initial: true) { _, problems in
441 if let first = problems.first {
442 commands.show(first + (problems.count > 1 ? " (and \(problems.count - 1) more)" : ""))
443 }
444 }
445 .onChange(of: ConfigSync.shared.changedFile?.serial) {
446 if ConfigSync.shared.changedFile?.name == "keymap.toml" { loadKeymap() }
447 }
448 .onChange(of: commands.jumpRequest?.id) {
449 guard let request = commands.jumpRequest else { return }
450 if request.path != session.path {
451 session.open(request.path)
452 selectedFile = request.path
453 }
454 session.reveal(request.offset)
455 }
456 .onChange(of: commands.focusSearch) { _, focus in
457 if focus {
458 searchFocused = true
459 commands.focusSearch = false
460 }
461 }
462 .fileImporter(isPresented: $commands.showingFolderPicker, allowedContentTypes: [.folder]) { result in
463 guard case .success(let url) = result else { return }
464 Task {
465 do { try await workspace.addRoot(url) } catch { workspace.lastError = error.localizedDescription }
466 }
467 }
468 .sheet(isPresented: $commands.showingQuickOpen) {
469 QuickOpenView(workspace: workspace) { entry in
470 commands.showingQuickOpen = false
471 DispatchQueue.main.async {
472 restoreSheetTarget()
473 selectedFile = entry.path
474 if selectedFile == entry.path { session.open(entry.path) }
475 }
476 }
477 }
478 .alert("orgstar", isPresented: errorShown) {
479 Button("OK") {
480 workspace.lastError = nil
481 session.lastError = nil
482 }
483 } message: {
484 Text(workspace.lastError ?? session.lastError ?? "")
485 }
486 .task(id: ReminderKey(
487 enabled: remindersEnabled, lead: reminderLead, subfolders: agendaSubfolders, hidden: HiddenFolders.shared.all, files: workspace.files.count,
488 changed: workspace.changedFile?.version, edits: session.editVersion, hour: hour, theme: theme
489 )) {
490 await updateReminders()
491 await updateWidgets()
492 }
493 .task {
494 while !Task.isCancelled {
495 try? await Task.sleep(for: .seconds(3600))
496 hour += 1
497 }
498 }
499 // `org-resolve-clocks-if-idle`, checked every minute while a clock runs.
500 .task(id: "\(clock.running?.start ?? "") \(clockIdleTime)") {
501 guard clock.running != nil, clockIdleTime > 0 else { return }
502 while !Task.isCancelled {
503 try? await Task.sleep(for: .seconds(60))
504 guard !Task.isCancelled, clock.running != nil, !clock.isResolving else { continue }
505 let idle = ClockIdle.seconds()
506 guard idle > Double(clockIdleTime * 60) else { continue }
507 NSApp.requestUserAttention(.informationalRequest)
508 report(await clock.resolveIdle(session, idleSince: Date().addingTimeInterval(-idle), ask: askClock))
509 }
510 }
511 .task {
512 #if !APPSTORE
513 DevelopmentHooks.scheduleSnapshot()
514 #endif
515 pendingCarets = BufferRestore.restore(session)
516 if let path = session.path, let caret = pendingCarets.removeValue(forKey: path) { session.reveal(caret) }
517 // Files handed over at launch open after the restored buffers, and show.
518 for path in AppDelegate.pendingOpens { session.open(path) }
519 AppDelegate.pendingOpens = []
520 #if APPSTORE
521 for link in AppDelegate.pendingLinks { commands.handle(protocolURL: link) }
522 AppDelegate.pendingLinks = []
523 #else
524 for link in AppDelegate.pendingLinks + [DevelopmentHooks.urlToOpen].compactMap({ $0 }) { commands.handle(protocolURL: link) }
525 AppDelegate.pendingLinks = []
526 if let path = DevelopmentHooks.fileToOpen { selectedFile = path }
527 if let root = DevelopmentHooks.rootToAdd { try? await workspace.addRoot(URL(fileURLWithPath: root)) }
528 if let commandList = DevelopmentHooks.commandToRun {
529 // The file opened above needs its editor first.
530 for _ in 0..<20 where DevelopmentHooks.fileToOpen != nil && commands.editor == nil { try? await Task.sleep(for: .milliseconds(100)) }
531 for command in commandList.split(separator: ",") { perform(String(command)) }
532 for answer in DevelopmentHooks.answers {
533 for _ in 0..<20 where commands.prompt == nil { try? await Task.sleep(for: .milliseconds(100)) }
534 commands.answer(answer)
535 }
536 }
537 if let id = DevelopmentHooks.windowToOpen {
538 if id == "settings" { openSettings() } else { openWindow(id: id) }
539 }
540 #endif
541 await workspace.refresh()
542 workspace.startWatching()
543 }
544 }
545
546 /// The selection, or the whole file without one, on the clipboard as HTML, RTF and plain
547 /// text, to paste formatted into mail and documents.
548 private func copyRichText() {
549 guard let path = session.path, let whole = session.document?.text, let editor = commands.editor else { return commands.show("No file is open") }
550 let defaults = Preferences.orgSettings.resolvingSetupFiles(in: whole, path: path, read: OrgSettings.readFile)
551 let selection = editor.context().selection.first { !$0.isEmpty }
552 let selected = selection.map { (whole as NSString).substring(with: NSRange($0)) }
553 let url = URL(fileURLWithPath: path)
554 let html = HTMLExport.page(
555 selected ?? whole, fallbackTitle: url.deletingPathExtension().lastPathComponent, settings: defaults, path: path, bodyOnly: selected != nil,
556 codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme), language: OrgPreferences.exportLanguage()
557 )
558 do {
559 try RichTextExport.copy(html: html, directory: url.deletingLastPathComponent())
560 commands.show(selected == nil ? "Copied the file as rich text" : "Copied the selection as rich text")
561 } catch {
562 commands.show("\(error)")
563 }
564 }
565
566 /// Whether the caret is in a heading's subtree, which the export dialog can export alone.
567 private var exportSubtreeAvailable: Bool {
568 guard let text = session.document?.text, let caret = commands.editor?.context().caret else { return false }
569 return ExportScope.subtree(text, at: caret) != nil
570 }
571
572 /// Where an export goes by default: `#+EXPORT_FILE_NAME`, or the subtree's
573 /// `EXPORT_FILE_NAME`, else beside the file, with `ext`.
574 private func exportTarget(_ ext: String, subtree: Bool) -> URL {
575 let path = session.path ?? ""
576 let text = session.document?.text ?? ""
577 let caret = subtree ? commands.editor?.context().caret : nil
578 return ExportScope.output(for: URL(fileURLWithPath: path), name: ExportScope.fileName(text, subtreeAt: caret), extension: ext)
579 }
580
581 /// Writes the export where `#+EXPORT_FILE_NAME` says or beside the file, as Emacs's export
582 /// dispatcher does, or to `destination`, and opens it with `open`. `subtree` exports the
583 /// subtree at the caret alone; `bodyOnly` leaves out the title and page wrapper.
584 private func export(_ format: String, to destination: URL? = nil, open: Bool = false, subtree: Bool = false, bodyOnly: Bool = false) {
585 if let feature = ProFeature.required(byExport: format), !ProAccess.shared.allows(feature) { return }
586 if format == "icalendar-agenda" || format == "icalendar-combined" { return exportAgendaCalendars(combined: format == "icalendar-combined") }
587 guard let path = session.path, var text = session.document?.text else {
588 commands.show("No file is open")
589 return
590 }
591 guard readsIncludes(text, path: path) else { return }
592 let url = URL(fileURLWithPath: path)
593 let base = url.deletingPathExtension()
594 let defaults = Preferences.orgSettings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
595 let open = open || format == "html-open"
596 let caret = commands.editor?.context().caret ?? 0
597 let whole = text
598 if subtree {
599 guard let narrowed = ExportScope.subtree(text, at: caret, settings: defaults) else { return commands.show("Not in a subtree") }
600 text = narrowed
601 }
602 switch format {
603 case "icalendar":
604 let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
605 guard let destination = destination ?? writable(ExportScope.output(for: url, name: name, extension: "ics")) else { return }
606 do {
607 let target = try ICalendarFiles.export(whole, path: path, settings: defaults, options: OrgPreferences.icalendarOptions(),
608 subtree: subtree ? caret : nil, destination: destination)
609 commands.show("Exported to \(target.lastPathComponent)")
610 if open { NSWorkspace.shared.open(target) }
611 } catch {
612 commands.show("Can't export: \(error.localizedDescription)")
613 }
614 case "html", "html-open", "markdown":
615 let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
616 guard let target = destination ?? writable(ExportScope.output(for: url, name: name, extension: format == "markdown" ? "md" : "html")) else { return }
617 let content = format == "markdown"
618 ? MarkdownExport.document(text, settings: defaults, path: path, bodyOnly: bodyOnly)
619 : HTMLExport.page(
620 text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path, bodyOnly: bodyOnly,
621 codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme), language: OrgPreferences.exportLanguage()
622 )
623 do {
624 try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
625 try content.write(to: target, atomically: true, encoding: .utf8)
626 commands.show("Exported to \(target.lastPathComponent)")
627 if open { NSWorkspace.shared.open(target) }
628 } catch {
629 commands.show("Can't write \(target.lastPathComponent): \(error.localizedDescription)")
630 }
631 case "latex" where exportLaTeX(text, whole: whole, url: url, to: destination, open: open, subtree: subtree ? caret : nil, bodyOnly: bodyOnly, settings: defaults):
632 break
633 case "odt":
634 let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
635 guard let target = destination ?? writable(ExportScope.output(for: url, name: name, extension: "odt")) else { return }
636 // A missing image stops the export, so offer access to them first.
637 _ = reach(ODTExport.imageFiles(text, settings: defaults, path: path).filter(WorkspaceModel.isThere))
638 do {
639 let data = try ODTExport.document(text, settings: defaults, path: path, author: NSFullUserName(), language: OrgPreferences.exportLanguage())
640 try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
641 try data.write(to: target, options: .atomic)
642 commands.show("Exported to \(target.lastPathComponent)")
643 if open { NSWorkspace.shared.open(target) }
644 } catch {
645 commands.show("Can't export \(target.lastPathComponent): \(error.localizedDescription)")
646 }
647 case "print-pdf", "docx", "rtf", "plain-text":
648 let ext = ["print-pdf": "pdf", "plain-text": "txt"][format] ?? format
649 let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
650 guard let target = destination ?? writable(ExportScope.output(for: url, name: name, extension: ext)) else { return }
651 let html = HTMLExport.page(
652 text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path,
653 codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme), language: OrgPreferences.exportLanguage()
654 )
655 let directory = url.deletingLastPathComponent()
656 // Images that can't be read are left out, so offer access to them first.
657 _ = reach(PDFExport.imageFiles(html, directory: directory).filter(WorkspaceModel.isThere))
658 if format == "print-pdf" { commands.show("Exporting to PDF…") }
659 Task {
660 do {
661 let data: Data
662 switch format {
663 case "print-pdf": data = try await PDFExport.pdf(html: html, directory: directory, options: OrgPreferences.pdfOptions())
664 case "docx": data = try RichTextExport.docx(html: html, directory: directory)
665 case "rtf": data = try RichTextExport.rtf(RichTextExport.attributed(html: html, directory: directory))
666 default: data = Data(RichTextExport.plain(try RichTextExport.attributed(html: html, directory: directory)).utf8)
667 }
668 try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
669 try data.write(to: target, options: .atomic)
670 commands.show("Exported to \(target.lastPathComponent)")
671 if open { NSWorkspace.shared.open(target) }
672 } catch {
673 commands.show("Can't export \(target.lastPathComponent): \(error)")
674 }
675 }
676 default:
677 #if !APPSTORE
678 let functions = ["pdf": "org-latex-export-to-pdf", "latex": "org-latex-export-to-latex", "text": "org-ascii-export-to-ascii"]
679 guard let function = functions[format] else { return }
680 commands.show("Exporting with Emacs…")
681 commands.runInEmacs {
682 do {
683 // Emacs narrows to the subtree and reads EXPORT_FILE_NAME itself.
684 let point = subtree ? (whole as NSString).substring(to: min(caret, (whole as NSString).length)).unicodeScalars.count + 1 : nil
685 var written = URL(fileURLWithPath: try await EmacsRunner.export(
686 text: whole, path: path, function: function, subtree: point, bodyOnly: bodyOnly
687 ))
688 if let destination, destination.standardizedFileURL != written.standardizedFileURL {
689 try? FileManager.default.removeItem(at: destination)
690 try FileManager.default.moveItem(at: written, to: destination)
691 written = destination
692 }
693 commands.show("Exported to \(written.lastPathComponent)")
694 if open { NSWorkspace.shared.open(written) }
695 } catch is CancellationError {
696 commands.show("Export canceled")
697 } catch {
698 commands.show("\(error)")
699 }
700 }
701 #else
702 let title = EditorCommands.all.first { $0.id == "app.export." + format }?.title
703 commands.show(Self.unavailable(title ?? format))
704 #endif
705 }
706 }
707
708 /// Writes `text` as LaTeX, as ox-latex does. False when the native export can't match Emacs
709 /// and Emacs is installed to export instead; otherwise the reason is shown.
710 private func exportLaTeX(_ text: String, whole: String, url: URL, to destination: URL?, open: Bool, subtree: Int?, bodyOnly: Bool, settings: OrgSettings) -> Bool {
711 let content: String
712 do {
713 content = try LaTeXExport.document(text, settings: settings, path: url.path, bodyOnly: bodyOnly, author: NSFullUserName(), language: OrgPreferences.exportLanguage(), file: true)
714 } catch {
715 #if !APPSTORE
716 if EmacsRunner.executable() != nil { return false }
717 #endif
718 commands.show("Can't export to LaTeX: \(error.localizedDescription)")
719 return true
720 }
721 let name = ExportScope.fileName(whole, subtreeAt: subtree, settings: settings)
722 guard let target = destination ?? writable(ExportScope.output(for: url, name: name, extension: "tex")) else { return true }
723 do {
724 try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
725 try content.write(to: target, atomically: true, encoding: .utf8)
726 commands.show("Exported to \(target.lastPathComponent)")
727 if open { NSWorkspace.shared.open(target) }
728 } catch {
729 commands.show("Can't write \(target.lastPathComponent): \(error.localizedDescription)")
730 }
731 return true
732 }
733
734 /// `url`; in the App Store build, when the sandbox keeps orgstar out of its folder, `url` once
735 /// that folder is granted, or where a save panel puts it instead. Nil when canceled.
736 private func writable(_ url: URL) -> URL? {
737 #if APPSTORE
738 guard let folder = workspace.foldersToGrant(for: [url.path]).first else { return url }
739 let elsewhere = String(localized: "Save Elsewhere…", comment: "Button that asks where an export goes instead")
740 switch GrantAccess.ask(folder, workspace: workspace, alternative: elsewhere) {
741 case .granted: return url
742 case .canceled: return nil
743 case .alternative: break
744 }
745 let panel = NSSavePanel()
746 panel.directoryURL = url.deletingLastPathComponent()
747 panel.nameFieldStringValue = url.lastPathComponent
748 panel.message = String(localized: "This file isn't in one of your folders. Choose where the export goes.", comment: "Save panel for an export outside the sidebar's folders")
749 return panel.runModal() == .OK ? panel.url : nil
750 #else
751 return url
752 #endif
753 }
754
755 private func saveBuffers() {
756 #if APPSTORE
757 BufferRestore.save(session, workspace: workspace)
758 #else
759 BufferRestore.save(session)
760 #endif
761 }
762
763 /// In the App Store build, asks for the folders outside the sidebar's folders that `paths`
764 /// need. False when one is still out of reach.
765 private func reach(_ paths: @autoclosure () -> [String], directories: Bool = false) -> Bool {
766 #if APPSTORE
767 GrantAccess.reach(paths(), directories: directories, workspace: workspace)
768 #else
769 true
770 #endif
771 }
772
773 /// In the App Store build, offers access to the setup files and includes of `text` that
774 /// can't be read. False, with a message, when an include still can't be read, rather than
775 /// exporting it as an empty line.
776 private func readsIncludes(_ text: String, path: String) -> Bool {
777 #if APPSTORE
778 let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
779 var setupFiles: [String] = []
780 _ = Preferences.orgSettings.resolvingSetupFiles(in: text, path: path) { file in
781 let contents = OrgSettings.readFile(file)
782 if contents == nil, WorkspaceModel.isThere(file) { setupFiles.append(file) }
783 return contents
784 }
785 let includes = ExportPreprocess.unreadableIncludes(text, directory: directory).filter(WorkspaceModel.isThere)
786 guard !(setupFiles + includes).isEmpty else { return true }
787 _ = reach(setupFiles + includes)
788 guard let unreadable = ExportPreprocess.unreadableIncludes(text, directory: directory).first else { return true }
789 commands.show(String(localized: "Can't include \(OrgPaths.abbreviatingWithTilde(unreadable)).", comment: "Export stopped by an #+INCLUDE file that can't be read"))
790 return false
791 #else
792 return true
793 #endif
794 }
795
796 /// Says a command doesn't run in this build.
797 static func unavailable(_ title: String) -> String {
798 String(localized: "\(CommandTitle.localized(title)) isn't available.", comment: "A command the Mac App Store build leaves out")
799 }
800
801 /// `org-icalendar-export-agenda-files`, or with `combined`, `org-icalendar-combine-agenda-files`.
802 private func exportAgendaCalendars(combined: Bool) {
803 let paths = workspace.agendaFilePaths()
804 guard reach(paths + (combined ? [OrgPreferences.icalendarCombinedFile()] : [])) else { return }
805 let read = { (path: String) -> (text: String, settings: OrgSettings)? in
806 guard let text = session.openDocuments.first(where: { $0.path == path })?.document.text ?? (try? String(contentsOfFile: path, encoding: .utf8)) else { return nil }
807 return (text, Preferences.orgSettings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile))
808 }
809 do {
810 let options = OrgPreferences.icalendarOptions()
811 if combined {
812 let url = try ICalendarFiles.combine(paths, to: OrgPreferences.icalendarCombinedFile(), options: options, read: read)
813 commands.show("Exported \(paths.count) agenda files to \(url.lastPathComponent)")
814 } else {
815 let written = try ICalendarFiles.exportEach(paths, options: options, read: read)
816 commands.show("Exported \(written.count) agenda files to iCalendar")
817 }
818 } catch {
819 commands.show("Can't export: \(error.localizedDescription)")
820 }
821 }
822
823 /// org-crypt's commands at the caret, through the passphrase sheet.
824 private func crypt(_ id: String) {
825 guard let editor = commands.editor, let path = session.path else { return commands.show("No file is open") }
826 let caret = editor.context().caret
827 let text = editor.context().text
828 switch id {
829 case "app.crypt.forget-passphrase":
830 CryptPassphrases.forget(path)
831 commands.show("Passphrase forgotten for \((path as NSString).lastPathComponent)")
832 case "app.crypt.encrypt-entries":
833 panel = .crypt(UUID(), CryptRequest(mode: .encryptAll(tag: OrgPreferences.cryptTag()), path: path, offset: caret))
834 default:
835 guard OrgCrypt.heading(text, at: caret) != nil else { return commands.show("Before first headline") }
836 if id == "app.crypt.encrypt-entry" {
837 guard OrgCrypt.encryptedRange(text, at: caret) == nil else { return commands.show("The entry is encrypted already") }
838 panel = .crypt(UUID(), CryptRequest(mode: .encrypt, path: path, offset: caret))
839 } else {
840 guard OrgCrypt.encryptedRange(text, at: caret) != nil else { return commands.show("Not an encrypted entry") }
841 panel = .crypt(UUID(), CryptRequest(mode: id == "app.crypt.open-entry" ? .open : .decryptInPlace, path: path, offset: caret))
842 }
843 }
844 }
845
846 /// org-roam's daily notes and nodes.
847 private var roamActions: RoamActions {
848 var actions = RoamActions(
849 session: session, roots: { [workspace] in workspace.rootPaths },
850 nodes: { [workspace, session] in workspace.nodes(overlay: workspace.overlay(session.openDocuments)) },
851 show: { [commands] in commands.show($0) }, ask: { [commands] in commands.ask($0, reply: $1) },
852 open: { [commands] path, offset in commands.jump(path: path, offset: offset) },
853 insertLink: { [commands] link, title in
854 guard let editor = commands.editor else { return commands.show("No file is open") }
855 let context = editor.context()
856 let range = context.selection.first ?? context.caret..<context.caret
857 let selected = (context.text as NSString).substring(with: NSRange(range))
858 let text = Links.makeString(link, selected.isEmpty ? title : selected)
859 let end = range.lowerBound + (text as NSString).length
860 editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: [TextEdit(range: range, replacement: text)], selection: [end..<end])))
861 },
862 refresh: { [workspace] in Task { await workspace.refresh() } })
863 #if APPSTORE
864 actions.reachFolders = { [workspace] in GrantAccess.reach($0, directories: true, workspace: workspace) }
865 #endif
866 return actions
867 }
868
869 /// org-attach's commands for the entry at the caret.
870 private var attachActions: AttachActions {
871 AttachActions(
872 entry: { [commands, session] in
873 guard let editor = commands.editor, let path = session.path else { return nil }
874 let context = editor.context()
875 return Attachments.Entry(text: context.text, offset: context.caret, path: path, options: context.options)
876 },
877 apply: { applyText($0, caret: $1) }, show: { [commands] in commands.show($0) }, ask: { [commands] in commands.ask($0, reply: $1) },
878 storeLink: { [commands] in _ = StoredLink.add($0, to: &commands.storedLinks) },
879 open: { [session, workspace, commands] file in
880 if let message = LinkOpener.open(OrgLink(type: "file", path: file, raw: "file:" + file), session: session, workspace: workspace, ask: commands.ask) { commands.show(message) }
881 },
882 reveal: { NSWorkspace.shared.open(URL(fileURLWithPath: $0, isDirectory: true)) },
883 pick: { method in
884 let panel = NSOpenPanel()
885 panel.canChooseDirectories = true
886 panel.allowsMultipleSelection = true
887 panel.message = "File to keep as an attachment"
888 guard panel.runModal() == .OK else { return }
889 #if APPSTORE
890 // The sandbox can remove only files in the sidebar's folders, and links nothing.
891 if method == .mv, let outside = panel.urls.first(where: { !workspace.contains($0) }) {
892 return commands.show(String(localized: "\(outside.lastPathComponent) isn't in one of your folders, so it can't be moved. Attach a copy instead.", comment: "Attach by moving a file from outside the sidebar's folders"))
893 }
894 guard method == .cp || method == .mv else { return }
895 #endif
896 attachActions.attach(panel.urls, method: method)
897 })
898 }
899
900 /// The sheet a panel shows.
901 @ViewBuilder
902 private func panelView(_ panel: Panel) -> some View {
903 switch panel {
904 case .columns(_, let view):
905 ColumnViewSheet(view: view, run: runInColumnView, document: { session.document.map { ($0.text, $0.tree) } }) { offset in
906 commands.editor?.reveal(offset)
907 }
908 case .export(_, let source):
909 ExportSheet(source: source, inSubtree: exportSubtreeAvailable, target: exportTarget) { format, destination, open, subtree, bodyOnly in
910 export(format, to: destination, open: open, subtree: subtree, bodyOnly: bodyOnly)
911 }
912 case .plot(_, let plot):
913 PlotSheet(content: .chart(plot))
914 case .plotImage(_, let url):
915 PlotSheet(content: .image(url))
916 case .crypt(_, let request):
917 CryptSheet(request: request, text: { session.document?.text ?? "" }, apply: { applyText($0) }) { message in
918 self.panel = nil
919 if let message { commands.show(message) }
920 }
921 case .conflict:
922 ConflictSheet(session: session)
923 case .syncCopies:
924 SyncConflictSheet(session: session) { commands.show($0) }
925 case .recovery:
926 RecoverySheet(session: session) { commands.show($0) }
927 }
928 }
929
930 /// `new` in place of the buffer's text, as one edit, with the caret at `caret` or where it was.
931 private func applyText(_ new: String, caret: Int? = nil) {
932 guard let editor = commands.editor else { return }
933 let context = editor.context()
934 let caret = min(caret ?? context.caret, (new as NSString).length)
935 editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
936 }
937
938 /// `org-plot/gnuplot` for the table at the caret: through gnuplot when it's installed, as
939 /// Emacs runs it, else drawn here; written to `file:` when the options name one, else shown.
940 private func plotTable() {
941 guard let editor = commands.editor, let path = session.path else { return commands.show("No file is open") }
942 let context = editor.context()
943 let plot: TablePlot.Plot
944 do { plot = try TablePlot.plot(context.text, at: context.caret) } catch { return commands.show("\(error)") }
945 let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
946 #if !APPSTORE
947 if let gnuplot = PlotOutput.gnuplot {
948 commands.show("Plotting with gnuplot…")
949 Task {
950 do {
951 let image = try await PlotOutput.runGnuplot(plot, directory: directory, gnuplot: gnuplot)
952 if plot.options.file == nil { panel = .plotImage(UUID(), image) } else { plotWritten(image, editor: editor) }
953 } catch {
954 commands.show("\(error)")
955 }
956 }
957 return
958 }
959 #endif
960 if let url = PlotOutput.file(plot, directory: directory) {
961 guard reach([url.path]) else { return }
962 do {
963 try PlotOutput.write(plot, to: url)
964 plotWritten(url, editor: editor)
965 } catch {
966 commands.show("\(error)")
967 }
968 } else {
969 panel = .plot(UUID(), plot)
970 }
971 }
972
973 /// The image is where `file:` says; a link to it shows it again.
974 private func plotWritten(_ url: URL, editor: OrgEditor) {
975 commands.show("Plot written to \(url.lastPathComponent)")
976 if editor.showsImages { editor.refreshImages() }
977 }
978
979 /// `org-publish`, `org-publish-all`, `org-publish-current-file` and
980 /// `org-publish-current-project`, with the projects in config.toml.
981 private func publish(_ id: String) {
982 let config = (try? String(contentsOf: UserConfig.file("config.toml"), encoding: .utf8)) ?? ""
983 let loaded = Publish.projects(fromConfig: config, root: workspace.rootPaths.first)
984 if let problem = loaded.problems.first { commands.show(problem) }
985 guard !loaded.projects.isEmpty else { return commands.show("No [[publish]] projects in config.toml") }
986 let read = { (path: String) -> String? in
987 session.openDocuments.first { $0.path == path }?.document.text ?? (try? String(contentsOfFile: path, encoding: .utf8))
988 }
989 let codeStyle = HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme)
990 func run(_ chosen: [PublishProject], only: String? = nil) {
991 // The chosen projects and their components read and write these folders.
992 let involved = { loaded.projects.filter { project in chosen.contains { $0 == project || $0.components.contains(project.name) } } }
993 guard reach(involved().flatMap { [$0.baseDirectory, $0.publishingDirectory] }, directories: true) else { return }
994 do {
995 let report = try Publish.publish(chosen, all: loaded.projects, only: only, read: read) { function, text, path, bodyOnly in
996 let settings = Preferences.orgSettings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
997 if function == "org-md-publish-to-md" { return MarkdownExport.document(text, settings: settings, path: path, bodyOnly: bodyOnly) }
998 if function == "org-latex-publish-to-latex" {
999 do {
1000 return try LaTeXExport.document(text, settings: settings, path: path, bodyOnly: bodyOnly, author: NSFullUserName(), language: OrgPreferences.exportLanguage(), file: true)
1001 } catch let error as LaTeXExport.Unsupported {
1002 throw LaTeXExport.Unsupported(reason: "Can't export \((path as NSString).lastPathComponent) to LaTeX: \(error.reason)")
1003 }
1004 }
1005 let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
1006 return HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, bodyOnly: bodyOnly, codeStyle: codeStyle, language: OrgPreferences.exportLanguage())
1007 }
1008 commands.show("Published \(report.published.count) files" + (report.skipped.isEmpty ? "" : ", \(report.skipped.count) up to date"))
1009 } catch {
1010 commands.show("\(error)")
1011 }
1012 }
1013 let current = session.path.map { Publish.projects(containing: $0, in: loaded.projects) } ?? []
1014 switch id {
1015 case "app.publish.all":
1016 run(loaded.projects)
1017 case "app.publish.current-file":
1018 guard let path = session.path, !current.isEmpty else { return commands.show("File is not part of any known project") }
1019 run([current[0]], only: path)
1020 case "app.publish.current-project":
1021 guard !current.isEmpty else { return commands.show("File is not part of any known project") }
1022 run([current[0]])
1023 default:
1024 let names = loaded.projects.map(\.name)
1025 commands.ask(Prompt(key: "project", message: "Publish project:", choices: names)) { answer in
1026 guard let answer, let project = loaded.projects.first(where: { $0.name == answer }) else { return }
1027 run([project])
1028 }
1029 }
1030 }
1031
1032 /// Work a command hands to the platform: tables recalculated in Emacs.
1033 private func runExternal(_ request: ExternalRequest) {
1034 switch request {
1035 case .openLink(let link):
1036 if let message = LinkOpener.open(link, session: session, workspace: workspace, ask: commands.ask) { commands.show(message) }
1037 // `org-occur` for a regexp link, once the editor shows the file.
1038 if let regexp = Links.regexpSearch(link) {
1039 DispatchQueue.main.async { commands.editor?.perform(SparseTreeCommand(), answers: ["sparse": "/", "regexp": regexp]) }
1040 }
1041 case .tangle(let scope):
1042 guard ProAccess.shared.allows(.babel), reach(session.tangleFiles(scope)) else { return }
1043 commands.show(session.tangle(scope))
1044 case .agenda(let start, let days):
1045 commands.agendaRequest = (start, days)
1046 openWindow(id: "agenda")
1047 case .editBlock(let edit):
1048 blockEdit = BlockEditRequest(edit: edit)
1049 case .columnView(let view):
1050 panel = .columns(UUID(), view)
1051 #if APPSTORE
1052 case .emacsTable(_, _, _, let reason, _):
1053 commands.show(String(localized: "This table's formulas can't be calculated here: \(TableReason.localized(reason)).", comment: "Table formulas orgstar can't calculate"))
1054 #else
1055 case .emacsTable(let table, let point, let form, let reason, let lisp):
1056 let run = {
1057 commands.show(String(localized: "Recalculating in Emacs (\(TableReason.localized(reason)))…", comment: "Table formulas sent to Emacs, and why"))
1058 commands.runInEmacs { commands.show(await session.recalculateInEmacs(table: table, point: point, form: form)) }
1059 }
1060 guard lisp, let path = session.path, let text = session.document?.text else { return run() }
1061 let content = (text as NSString).substring(with: NSRange(location: table.lowerBound, length: min((text as NSString).length, table.upperBound + 2000) - table.lowerBound))
1062 if trust.isTrusted(path: path, content: content) { return run() }
1063 commands.ask(Prompt(key: "confirm", message: "This table's formulas run Lisp. Run them? (yes, no, always)", choices: ["yes", "no", "always"])) { answer in
1064 switch answer {
1065 case "always":
1066 trust.trust(path: path, content: content)
1067 run()
1068 case "yes": run()
1069 default: commands.show("Not recalculated")
1070 }
1071 }
1072 #endif
1073 case .babel(let job):
1074 guard ProAccess.shared.allows(.babel) else { return }
1075 let run = {
1076 guard reach(session.resultFile(of: job).map { [$0] } ?? []) else { return }
1077 commands.show("Running \(job.language) block… (⌘. to cancel)")
1078 session.startBabel(job) { commands.show($0) }
1079 }
1080 guard let path = session.path else { return }
1081 if !job.alwaysAsk, trust.isTrusted(path: path, content: job.blockText) { return run() }
1082 let choices = job.alwaysAsk ? ["yes", "no"] : ["yes", "no", "always"]
1083 commands.ask(Prompt(key: "confirm", message: "Run this \(job.language) block? (\(choices.joined(separator: ", ")))", choices: choices)) { answer in
1084 switch answer {
1085 case "always":
1086 trust.trust(path: path, content: job.blockText)
1087 run()
1088 case "yes": run()
1089 default: commands.show("Not run")
1090 }
1091 }
1092 }
1093 }
1094
1095 private struct ReminderKey: Equatable {
1096 var enabled: Bool
1097 var lead: Int
1098 var subfolders: Bool
1099 /// The widgets leave out hidden folders.
1100 var hidden: Set<String>
1101 var files: Int
1102 var changed: Int?
1103 var edits: Int
1104 var hour: Int
1105 /// The widgets' colors.
1106 var theme: ThemeSpec
1107 }
1108
1109 /// Sets the notifications for the next week's timed entries, once edits pause.
1110 private func updateReminders() async {
1111 guard let scheduler else { return }
1112 guard remindersEnabled else {
1113 await scheduler.clear()
1114 return
1115 }
1116 try? await Task.sleep(for: .seconds(2))
1117 guard !Task.isCancelled, !workspace.files.isEmpty else { return }
1118 let agenda = reminderAgenda ?? AgendaModel(workspace: workspace)
1119 reminderAgenda = agenda
1120 agenda.includeSubfolders = agendaSubfolders
1121 agenda.excludeArchives = OrgPreferences.agendaExcludeArchives()
1122 let open = session.openTexts
1123 let reminders = await agenda.reminders(open: open, lead: reminderLead)
1124 guard !Task.isCancelled else { return }
1125 await scheduler.reconcile(reminders)
1126 }
1127
1128 /// The desktop widgets' agenda and habits, written where the widget extension reads them,
1129 /// with the widgets reloaded when they changed.
1130 private func updateWidgets() async {
1131 guard !Task.isCancelled, ProAccess.shared.isUnlocked, !workspace.files.isEmpty, let file = AgendaSnapshot.file() else { return }
1132 let days = widgetAgenda ?? AgendaModel(workspace: workspace)
1133 widgetAgenda = days
1134 days.mode = .agenda(span: AgendaSnapshot.dayCount, startOffset: 0)
1135 days.startOnWeekday = nil
1136 days.includeSubfolders = agendaSubfolders
1137 days.excludeArchives = OrgPreferences.agendaExcludeArchives()
1138 days.hiddenFolders = HiddenFolders.shared.all
1139 days.agendaFiles = OrgPreferences.agendaFiles()
1140 days.options = OrgPreferences.agendaOptions(days.options)
1141 days.options.logMode = false
1142 days.calendarEvents = ProAccess.shared.isUnlocked && OrgPreferences.calendarEvents() && CalendarEvents.isAuthorized ? CalendarAccess.events : nil
1143 days.calendarNames = OrgPreferences.calendarEventCalendars()
1144 days.reminderLists = ProAccess.shared.isUnlocked && OrgPreferences.agendaReminders() && ReminderLists.isAuthorized ? CalendarAccess.reminders : nil
1145 days.reminderListNames = OrgPreferences.agendaReminderLists()
1146 let open = session.openTexts
1147 await days.refresh(open: open)
1148 guard !Task.isCancelled else { return }
1149 if (try? HabitSnapshot(habits: await days.habits(open: open), theme: theme).write()) == true {
1150 WidgetCenter.shared.reloadTimelines(ofKind: "sh.krz.orgstar.habits")
1151 }
1152 let snapshot = AgendaSnapshot(groups: days.groups(), today: days.today, theme: theme, generated: Date())
1153 if (try? snapshot.write(to: file)) == true { WidgetCenter.shared.reloadAllTimelines() }
1154 }
1155
1156 private func loadKeymap() {
1157 let loaded = KeymapLoader.load(preset, commands: Set(EditorCommands.all.map(\.id)))
1158 keymap = loaded.keymap
1159 commands.keymap = loaded.keymap
1160 commands.modal = preset.isModal
1161 if let first = loaded.problems.first {
1162 let more = loaded.problems.count > 1 ? " (and \(loaded.problems.count - 1) more)" : ""
1163 commands.show("keymap.toml: \(first)\(more)")
1164 }
1165 }
1166
1167 /// `SPC b b`: open buffers, most recent first, by name (with the folder when names repeat).
1168 private func switchBuffer() {
1169 let paths = session.recentPaths.dropFirst() + session.recentPaths.prefix(1)
1170 let labels = paths.map(session.bufferName)
1171 guard !labels.isEmpty else { return commands.show("No buffers are open") }
1172 commands.ask(Prompt(key: "buffer", message: "Switch to buffer:", choices: labels)) { answer in
1173 guard let answer, let index = labels.firstIndex(of: answer) else { return }
1174 session.open(Array(paths)[index])
1175 }
1176 }
1177
1178 /// Runs a command from a key, the palette or the Org menu.
1179 private func perform(_ id: String) {
1180 if hiddenCommandIDs.contains(id) {
1181 if let replacement = AppStoreCommands.replacement(for: id) { return perform(replacement) }
1182 return commands.show(Self.unavailable(EditorCommands.all.first { $0.id == id }?.title ?? id))
1183 }
1184 if let feature = ProFeature.required(byCommand: id), !ProAccess.shared.allows(feature) { return }
1185 let orgOnly = ["app.refile", "app.refile.copy", "app.archive", "app.clock.in", "app.clock.default", "app.copy-rich-text"].contains(id) || (id.hasPrefix("app.export.") && !id.hasPrefix("app.export.icalendar-")) || id.hasPrefix("org.")
1186 if orgOnly, !session.isOrg {
1187 commands.show("Not an org file")
1188 return
1189 }
1190 switch id {
1191 case "app.save":
1192 if !session.save(), session.conflict != nil { commands.showingConflict = true }
1193 case "app.quit": NSApp.terminate(nil)
1194 case "app.save-all":
1195 if !session.saveAll(), session.conflict != nil { commands.showingConflict = true }
1196 case "app.buffer.switch": switchBuffer()
1197 case "app.buffer.next": session.cycle(1)
1198 case "app.buffer.previous": session.cycle(-1)
1199 case "app.buffer.last": session.showPrevious()
1200 case "app.buffer.kill":
1201 if let window = paneWindow, window.paneCount > 1 {
1202 window.closeTab(session.path, in: window.focusedPane, commands: commands)
1203 } else if let path = session.path {
1204 if UnsavedChanges.resolve(session) { session.kill(path) }
1205 } else {
1206 NSApp.keyWindow?.performClose(nil)
1207 }
1208 case "app.buffer.kill-others":
1209 let others = session.openPaths.filter { $0 != session.path }
1210 if UnsavedChanges.resolve(session, paths: others) { others.forEach(session.kill) }
1211 case "app.buffer.kill-all":
1212 let all = session.openPaths
1213 if UnsavedChanges.resolve(session, paths: all) { all.forEach(session.kill) }
1214 case "app.toggle-tab-bar": showTabBar.toggle()
1215 case "app.split-below": paneWindow?.split(.vertical)
1216 case "app.split-right": paneWindow?.split(.horizontal)
1217 case "app.pane-close":
1218 guard let window = paneWindow, window.paneCount > 1 else { return commands.show("Attempt to delete the only pane") }
1219 commands.store.releasePane(window.focused)
1220 window.close(window.focused)
1221 focusPane(window)
1222 case "app.pane-only":
1223 guard let window = paneWindow else { return }
1224 for id in window.layout.panes where id != window.focused { commands.store.releasePane(id) }
1225 window.closeOthers()
1226 focusPane(window)
1227 case "app.pane-next":
1228 guard let window = paneWindow else { return }
1229 window.focusNext()
1230 focusPane(window)
1231 case "app.window-new": openWindow(id: "editor")
1232 case "app.babel.cancel":
1233 if session.isRunningBabel {
1234 session.cancelBabel()
1235 } else if let task = commands.emacsTask {
1236 task.cancel()
1237 } else {
1238 commands.show("Nothing is running")
1239 }
1240 case "app.toggle-outline": toggleOutline()
1241 case "app.toggle-backlinks": backlinksShown.toggle()
1242 case "app.toggle-inspector": inspectorShown.toggle()
1243 case "app.toggle-markup": showMarkup.toggle()
1244 case "app.toggle-line-numbers": showLineNumbers.toggle()
1245 case "app.import-emacs": showingImport = true
1246 case "app.edit-config": commands.jump(path: UserConfig.configFile.path, offset: 0)
1247 case "app.quick-open": commands.showingQuickOpen = true
1248 case "app.palette": commands.showingPalette = true
1249 case "app.search": commands.focusSearch = true
1250 case "app.reload-keymap":
1251 loadKeymap()
1252 commands.show("Keymap reloaded")
1253 case "app.refile", "app.refile.copy":
1254 let keep = id == "app.refile.copy"
1255 let targets = workspace.refileTargets(openPath: session.path, document: session.document)
1256 commands.ask(Prompt(key: "refile", message: keep ? "Copy to:" : "Refile to:", choices: targets.map(\.label))) { answer in
1257 guard let answer else { return }
1258 if let target = targets.first(where: { $0.label == answer }) {
1259 if let message = session.refile(to: target, keep: keep) { commands.show(message) }
1260 return
1261 }
1262 // `org-refile-allow-creating-parent-nodes`: `parent/new` adds the heading first.
1263 let creating = OrgPreferences.refileSettings().creating
1264 guard creating != .no, let (parent, child) = RefileSettings.newNode(answer, in: targets) else { return commands.show("Invalid target location") }
1265 let create = {
1266 switch session.createRefileChild(under: parent, title: child) {
1267 case .success(let target): if let message = session.refile(to: target, keep: keep) { commands.show(message) }
1268 case .failure(.message(let message)): commands.show(message)
1269 }
1270 }
1271 guard creating == .confirm else { return create() }
1272 commands.ask(Prompt(key: "confirm", message: "Create new node \"\(child)\"?", choices: ["yes", "no"])) { reply in
1273 if reply == "yes" { create() }
1274 }
1275 }
1276 case "app.refile.goto":
1277 // `C-u C-c C-w`: the target heading, or the end of a file.
1278 let targets = workspace.refileTargets(openPath: session.path, document: session.document)
1279 commands.ask(Prompt(key: "refile", message: "Goto:", choices: targets.map(\.label))) { answer in
1280 guard let answer, let target = targets.first(where: { $0.label == answer }) else { return }
1281 commands.jump(path: target.path, offset: target.start ?? Int.max)
1282 }
1283 case "app.archive":
1284 guard reach(session.archiveFile().map { [$0] } ?? []) else { return }
1285 if let message = session.archive() { commands.show(message) }
1286 case "app.table-import":
1287 // `org-table-import`: a TSV, CSV or space-separated file becomes a table at point.
1288 guard let editor = commands.editor else { return commands.show("No file is open") }
1289 let panel = NSOpenPanel()
1290 panel.allowedContentTypes = [.commaSeparatedText, .tabSeparatedText, .plainText]
1291 guard panel.runModal() == .OK, let url = panel.url else { return }
1292 guard let contents = try? String(contentsOf: url, encoding: .utf8) else { return commands.show("Can't read \(url.lastPathComponent)") }
1293 editor.perform(ImportTable(contents: contents))
1294 case "app.table-export":
1295 // `org-table-export`: CSV for a .csv name, else TSV.
1296 guard let editor = commands.editor else { return commands.show("No file is open") }
1297 let context = editor.context()
1298 guard ImportTable.exportText(context.text, at: context.caret, path: "") != nil else { return commands.show("No table at point") }
1299 let panel = NSSavePanel()
1300 panel.nameFieldStringValue = "table.csv"
1301 guard panel.runModal() == .OK, let url = panel.url,
1302 let text = ImportTable.exportText(context.text, at: context.caret, path: url.path) else { return }
1303 do {
1304 try text.write(to: url, atomically: true, encoding: .utf8)
1305 commands.show("Export done.")
1306 } catch {
1307 commands.show("File not written: \(error.localizedDescription)")
1308 }
1309 case "org.subtree.paste":
1310 guard let text = NSPasteboard.general.string(forType: .string) else { return commands.show("The clipboard is empty") }
1311 commands.editor?.perform(PasteSubtree(text: text))
1312 case "org.link.insert":
1313 commands.editor?.perform(InsertLink(stored: commands.storedLinks, file: session.path))
1314 case "org.link.store":
1315 guard let editor = commands.editor, let path = session.path else { return commands.show("No method for storing a link from this buffer") }
1316 let context = editor.context()
1317 let denote = OrgPreferences.usesDenote() ? Links.storeDenote(in: context, path: path) : nil
1318 commands.storeLink(denote ?? Links.store(in: context, path: Links.abbreviate(path, home: OrgPaths.home)))
1319 case "org.id.store-link":
1320 guard let editor = commands.editor, let path = session.path else { return }
1321 if case .commit = editor.perform(CreateID()),
1322 let link = Links.storeID(in: editor.context(), fileName: (path as NSString).lastPathComponent) {
1323 commands.storeLink(link)
1324 }
1325 case "app.agenda":
1326 openWindow(id: "agenda")
1327 case "app.clock.in":
1328 clockIn(.caret)
1329 case "app.clock.in-recent":
1330 clockIn(.select)
1331 case "app.clock.in-last":
1332 clockIn(.last)
1333 case let id where id.hasPrefix("app.clock.history."):
1334 if let index = Int(id.dropFirst("app.clock.history.".count)), index < clock.history.count { clockIn(.task(clock.history[index])) }
1335 case "app.clock.out":
1336 commands.show(clock.clockOut(session))
1337 case "app.clock.cancel":
1338 commands.show(clock.clockOut(session, cancel: true))
1339 case "app.clock.goto":
1340 let found = clock.goto(session)
1341 if let location = found.location { commands.jump(path: location.path, offset: location.offset) }
1342 if let message = found.message { commands.show(message) }
1343 case "app.clock.goto-recent":
1344 Task {
1345 let found = await clock.gotoRecent(session, ask: askClock)
1346 if let location = found.location { commands.jump(path: location.path, offset: location.offset) }
1347 if let message = found.message { commands.show(message) }
1348 }
1349 case "app.clock.default":
1350 commands.show(clock.markDefault(session))
1351 case "app.clock.resolve":
1352 Task { report(await clock.resolveOpenClocks(session, paths: orgFiles, ask: askClock)) }
1353 case "app.clock.report":
1354 openWindow(id: "clock-report")
1355 case "app.board":
1356 openWindow(id: "board")
1357 case "app.capture":
1358 NSApp.activate()
1359 openWindow(id: "capture")
1360 case "app.revert":
1361 // `:e`: the file as it is on disk; unsaved changes go to recovery.
1362 guard session.path != nil else { return commands.show("No file is open") }
1363 session.useDiskVersion()
1364 commands.show("Reverted to the file on disk")
1365 case "app.sync-conflicts":
1366 guard session.path != nil else { return commands.show("No file is open") }
1367 panel = .syncCopies(UUID())
1368 case "app.recovery":
1369 guard session.path != nil else { return commands.show("No file is open") }
1370 panel = .recovery(UUID())
1371 case "app.copy-rich-text":
1372 copyRichText()
1373 case "app.export-dialog":
1374 guard let path = session.path else { return commands.show("No file is open") }
1375 panel = .export(UUID(), URL(fileURLWithPath: path))
1376 case let id where id.hasPrefix("app.export."):
1377 export(String(id.dropFirst("app.export.".count)))
1378 case let id where id.hasPrefix("app.publish"):
1379 publish(id)
1380 case "app.plot":
1381 plotTable()
1382 case let id where id.hasPrefix("app.crypt."):
1383 crypt(id)
1384 case let id where id.hasPrefix("app.attach."):
1385 guard reach(attachActions.entry().flatMap { Attachments.directory($0, noFSCheck: true) }.map { [$0] } ?? [], directories: true) else { return }
1386 attachActions.run(id)
1387 case let id where id.hasPrefix("app.dailies.") || id.hasPrefix("app.node."):
1388 roamActions.run(id)
1389 default:
1390 if let editor = commands.editor { editor.run(id) } else { commands.show("No file is open") }
1391 }
1392 }
1393
1394 private var askClock: ClockModel.Ask { commands.askClock }
1395
1396 /// The files `org-resolve-clocks` looks through: the workspace's org files.
1397 private var orgFiles: [String] { workspace.files.filter { $0.kind == .org }.map(\.path) }
1398
1399 private func clockIn(_ target: ClockModel.Target) {
1400 Task { report(await clock.clockIn(session, target: target, paths: orgFiles, ask: askClock)) }
1401 }
1402
1403 /// The last message of a clock command, and the clock to show for `j`.
1404 private func report(_ outcome: ClockModel.Outcome) {
1405 if let jump = outcome.jump { commands.jump(path: jump.path, offset: jump.offset) }
1406 if let message = outcome.messages.last(where: { !$0.isEmpty }) { commands.show(message) }
1407 }
1408
1409 private var errorShown: Binding<Bool> {
1410 Binding(get: { workspace.lastError != nil || session.lastError != nil }, set: { _ in })
1411 }
1412}