Sources/Orgstar/ContentView.swift
cmc Share the publishing exporter, keep publishing folders as bookmarks, idle time from background time
f27a6bd93c 5 days ago1456 lines · 80652 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 exportNative("LaTeX", extension: "tex", whole: whole, url: url, to: destination, open: open, subtree: subtree ? caret : nil, settings: defaults, export: {
632 try LaTeXExport.document(text, settings: defaults, path: path, bodyOnly: bodyOnly, author: NSFullUserName(), language: OrgPreferences.exportLanguage(), file: true)
633 }):
634 break
635 case "text" where exportNative("plain text", extension: "txt", whole: whole, url: url, to: destination, open: open, subtree: subtree ? caret : nil, settings: defaults, export: {
636 try ASCIIExport.document(text, settings: defaults, path: path, bodyOnly: bodyOnly, author: NSFullUserName(), language: OrgPreferences.exportLanguage(), file: true)
637 }):
638 break
639 case "odt":
640 let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
641 guard let target = destination ?? writable(ExportScope.output(for: url, name: name, extension: "odt")) else { return }
642 // A missing image stops the export, so offer access to them first.
643 _ = reach(ODTExport.imageFiles(text, settings: defaults, path: path).filter(WorkspaceModel.isThere))
644 do {
645 let data = try ODTExport.document(text, settings: defaults, path: path, author: NSFullUserName(), language: OrgPreferences.exportLanguage())
646 try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
647 try data.write(to: target, options: .atomic)
648 commands.show("Exported to \(target.lastPathComponent)")
649 if open { NSWorkspace.shared.open(target) }
650 } catch {
651 commands.show("Can't export \(target.lastPathComponent): \(error.localizedDescription)")
652 }
653 case "print-pdf", "docx", "rtf", "plain-text":
654 let ext = ["print-pdf": "pdf", "plain-text": "txt"][format] ?? format
655 let name = ExportScope.fileName(whole, subtreeAt: subtree ? caret : nil, settings: defaults)
656 guard let target = destination ?? writable(ExportScope.output(for: url, name: name, extension: ext)) else { return }
657 let html = HTMLExport.page(
658 text, fallbackTitle: base.lastPathComponent, settings: defaults, path: path,
659 codeStyle: HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme), language: OrgPreferences.exportLanguage()
660 )
661 let directory = url.deletingLastPathComponent()
662 // Images that can't be read are left out, so offer access to them first.
663 _ = reach(PDFExport.imageFiles(html, directory: directory).filter(WorkspaceModel.isThere))
664 if format == "print-pdf" { commands.show("Exporting to PDF…") }
665 Task {
666 do {
667 let data: Data
668 switch format {
669 case "print-pdf": data = try await PDFExport.pdf(html: html, directory: directory, options: OrgPreferences.pdfOptions())
670 case "docx": data = try RichTextExport.docx(html: html, directory: directory)
671 case "rtf": data = try RichTextExport.rtf(RichTextExport.attributed(html: html, directory: directory))
672 default: data = Data(RichTextExport.plain(try RichTextExport.attributed(html: html, directory: directory)).utf8)
673 }
674 try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
675 try data.write(to: target, options: .atomic)
676 commands.show("Exported to \(target.lastPathComponent)")
677 if open { NSWorkspace.shared.open(target) }
678 } catch {
679 commands.show("Can't export \(target.lastPathComponent): \(error)")
680 }
681 }
682 default:
683 #if !APPSTORE
684 let functions = ["pdf": "org-latex-export-to-pdf", "latex": "org-latex-export-to-latex", "text": "org-ascii-export-to-ascii"]
685 guard let function = functions[format] else { return }
686 commands.show("Exporting with Emacs…")
687 commands.runInEmacs {
688 do {
689 // Emacs narrows to the subtree and reads EXPORT_FILE_NAME itself.
690 let point = subtree ? (whole as NSString).substring(to: min(caret, (whole as NSString).length)).unicodeScalars.count + 1 : nil
691 var written = URL(fileURLWithPath: try await EmacsRunner.export(
692 text: whole, path: path, function: function, subtree: point, bodyOnly: bodyOnly
693 ))
694 if let destination, destination.standardizedFileURL != written.standardizedFileURL {
695 try? FileManager.default.removeItem(at: destination)
696 try FileManager.default.moveItem(at: written, to: destination)
697 written = destination
698 }
699 commands.show("Exported to \(written.lastPathComponent)")
700 if open { NSWorkspace.shared.open(written) }
701 } catch is CancellationError {
702 commands.show("Export canceled")
703 } catch {
704 commands.show("\(error)")
705 }
706 }
707 #else
708 let title = EditorCommands.all.first { $0.id == "app.export." + format }?.title
709 commands.show(Self.unavailable(title ?? format))
710 #endif
711 }
712 }
713
714 /// Writes what `export` makes, as ox does for `format`. False when the native export can't
715 /// match Emacs and Emacs is installed to export instead; otherwise the reason is shown.
716 private func exportNative(
717 _ format: String, extension ext: String, whole: String, url: URL, to destination: URL?, open: Bool, subtree: Int?, settings: OrgSettings,
718 export: () throws -> String
719 ) -> Bool {
720 let content: String
721 do {
722 content = try export()
723 } catch {
724 #if !APPSTORE
725 if EmacsRunner.executable() != nil { return false }
726 #endif
727 commands.show("Can't export to \(format): \(error.localizedDescription)")
728 return true
729 }
730 let name = ExportScope.fileName(whole, subtreeAt: subtree, settings: settings)
731 guard let target = destination ?? writable(ExportScope.output(for: url, name: name, extension: ext)) else { return true }
732 do {
733 try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)
734 try content.write(to: target, atomically: true, encoding: .utf8)
735 commands.show("Exported to \(target.lastPathComponent)")
736 if open { NSWorkspace.shared.open(target) }
737 } catch {
738 commands.show("Can't write \(target.lastPathComponent): \(error.localizedDescription)")
739 }
740 return true
741 }
742
743 /// `url`; in the App Store build, when the sandbox keeps orgstar out of its folder, `url` once
744 /// that folder is granted, or where a save panel puts it instead. Nil when canceled.
745 private func writable(_ url: URL) -> URL? {
746 #if APPSTORE
747 guard let folder = workspace.foldersToGrant(for: [url.path]).first else { return url }
748 let elsewhere = String(localized: "Save Elsewhere…", comment: "Button that asks where an export goes instead")
749 switch GrantAccess.ask(folder, workspace: workspace, alternative: elsewhere) {
750 case .granted: return url
751 case .canceled: return nil
752 case .alternative: break
753 }
754 let panel = NSSavePanel()
755 panel.directoryURL = url.deletingLastPathComponent()
756 panel.nameFieldStringValue = url.lastPathComponent
757 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")
758 return panel.runModal() == .OK ? panel.url : nil
759 #else
760 return url
761 #endif
762 }
763
764 private func saveBuffers() {
765 #if APPSTORE
766 BufferRestore.save(session, workspace: workspace)
767 #else
768 BufferRestore.save(session)
769 #endif
770 }
771
772 /// In the App Store build, asks for the folders outside the sidebar's folders that `paths`
773 /// need. False when one is still out of reach.
774 private func reach(_ paths: @autoclosure () -> [String], directories: Bool = false) -> Bool {
775 #if APPSTORE
776 GrantAccess.reach(paths(), directories: directories, workspace: workspace)
777 #else
778 true
779 #endif
780 }
781
782 /// In the App Store build, offers access to the setup files and includes of `text` that
783 /// can't be read. False, with a message, when an include still can't be read, rather than
784 /// exporting it as an empty line.
785 private func readsIncludes(_ text: String, path: String) -> Bool {
786 #if APPSTORE
787 let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
788 var setupFiles: [String] = []
789 _ = Preferences.orgSettings.resolvingSetupFiles(in: text, path: path) { file in
790 let contents = OrgSettings.readFile(file)
791 if contents == nil, WorkspaceModel.isThere(file) { setupFiles.append(file) }
792 return contents
793 }
794 let includes = ExportPreprocess.unreadableIncludes(text, directory: directory).filter(WorkspaceModel.isThere)
795 guard !(setupFiles + includes).isEmpty else { return true }
796 _ = reach(setupFiles + includes)
797 guard let unreadable = ExportPreprocess.unreadableIncludes(text, directory: directory).first else { return true }
798 commands.show(String(localized: "Can't include \(OrgPaths.abbreviatingWithTilde(unreadable)).", comment: "Export stopped by an #+INCLUDE file that can't be read"))
799 return false
800 #else
801 return true
802 #endif
803 }
804
805 /// Says a command doesn't run in this build.
806 static func unavailable(_ title: String) -> String {
807 String(localized: "\(CommandTitle.localized(title)) isn't available.", comment: "A command the Mac App Store build leaves out")
808 }
809
810 /// `org-icalendar-export-agenda-files`, or with `combined`, `org-icalendar-combine-agenda-files`.
811 private func exportAgendaCalendars(combined: Bool) {
812 let paths = workspace.agendaFilePaths()
813 guard reach(paths + (combined ? [OrgPreferences.icalendarCombinedFile()] : [])) else { return }
814 let read = { (path: String) -> (text: String, settings: OrgSettings)? in
815 guard let text = session.openDocuments.first(where: { $0.path == path })?.document.text ?? (try? String(contentsOfFile: path, encoding: .utf8)) else { return nil }
816 return (text, Preferences.orgSettings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile))
817 }
818 do {
819 let options = OrgPreferences.icalendarOptions()
820 if combined {
821 let url = try ICalendarFiles.combine(paths, to: OrgPreferences.icalendarCombinedFile(), options: options, read: read)
822 commands.show("Exported \(paths.count) agenda files to \(url.lastPathComponent)")
823 } else {
824 let written = try ICalendarFiles.exportEach(paths, options: options, read: read)
825 commands.show("Exported \(written.count) agenda files to iCalendar")
826 }
827 } catch {
828 commands.show("Can't export: \(error.localizedDescription)")
829 }
830 }
831
832 /// org-crypt's commands at the caret, through the passphrase sheet.
833 private func crypt(_ id: String) {
834 guard let editor = commands.editor, let path = session.path else { return commands.show("No file is open") }
835 let caret = editor.context().caret
836 let text = editor.context().text
837 switch id {
838 case "app.crypt.forget-passphrase":
839 CryptPassphrases.forget(path)
840 commands.show("Passphrase forgotten for \((path as NSString).lastPathComponent)")
841 case "app.crypt.encrypt-entries":
842 panel = .crypt(UUID(), CryptRequest(mode: .encryptAll(tag: OrgPreferences.cryptTag()), path: path, offset: caret))
843 default:
844 guard OrgCrypt.heading(text, at: caret) != nil else { return commands.show("Before first headline") }
845 if id == "app.crypt.encrypt-entry" {
846 guard OrgCrypt.encryptedRange(text, at: caret) == nil else { return commands.show("The entry is encrypted already") }
847 panel = .crypt(UUID(), CryptRequest(mode: .encrypt, path: path, offset: caret))
848 } else {
849 guard OrgCrypt.encryptedRange(text, at: caret) != nil else { return commands.show("Not an encrypted entry") }
850 panel = .crypt(UUID(), CryptRequest(mode: id == "app.crypt.open-entry" ? .open : .decryptInPlace, path: path, offset: caret))
851 }
852 }
853 }
854
855 /// org-roam's daily notes and nodes.
856 private var roamActions: RoamActions {
857 var actions = RoamActions(
858 session: session, roots: { [workspace] in workspace.rootPaths },
859 nodes: { [workspace, session] in workspace.nodes(overlay: workspace.overlay(session.openDocuments)) },
860 show: { [commands] in commands.show($0) }, ask: { [commands] in commands.ask($0, reply: $1) },
861 open: { [commands] path, offset in commands.jump(path: path, offset: offset) },
862 insertLink: { [commands] link, title in
863 guard let editor = commands.editor else { return commands.show("No file is open") }
864 let context = editor.context()
865 let range = context.selection.first ?? context.caret..<context.caret
866 let selected = (context.text as NSString).substring(with: NSRange(range))
867 let text = Links.makeString(link, selected.isEmpty ? title : selected)
868 let end = range.lowerBound + (text as NSString).length
869 editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: [TextEdit(range: range, replacement: text)], selection: [end..<end])))
870 },
871 refresh: { [workspace] in Task { await workspace.refresh() } })
872 #if APPSTORE
873 actions.reachFolders = { [workspace] in GrantAccess.reach($0, directories: true, workspace: workspace) }
874 #endif
875 return actions
876 }
877
878 /// org-attach's commands for the entry at the caret.
879 private var attachActions: AttachActions {
880 AttachActions(
881 entry: { [commands, session] in
882 guard let editor = commands.editor, let path = session.path else { return nil }
883 let context = editor.context()
884 return Attachments.Entry(text: context.text, offset: context.caret, path: path, options: context.options)
885 },
886 apply: { applyText($0, caret: $1) }, show: { [commands] in commands.show($0) }, ask: { [commands] in commands.ask($0, reply: $1) },
887 storeLink: { [commands] in _ = StoredLink.add($0, to: &commands.storedLinks) },
888 open: { [session, workspace, commands] file in
889 if let message = LinkOpener.open(OrgLink(type: "file", path: file, raw: "file:" + file), session: session, workspace: workspace, ask: commands.ask) { commands.show(message) }
890 },
891 reveal: { NSWorkspace.shared.open(URL(fileURLWithPath: $0, isDirectory: true)) },
892 pick: { method in
893 let panel = NSOpenPanel()
894 panel.canChooseDirectories = true
895 panel.allowsMultipleSelection = true
896 panel.message = "File to keep as an attachment"
897 guard panel.runModal() == .OK else { return }
898 #if APPSTORE
899 // The sandbox can remove only files in the sidebar's folders, and links nothing.
900 if method == .mv, let outside = panel.urls.first(where: { !workspace.contains($0) }) {
901 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"))
902 }
903 guard method == .cp || method == .mv else { return }
904 #endif
905 attachActions.attach(panel.urls, method: method)
906 })
907 }
908
909 /// The sheet a panel shows.
910 @ViewBuilder
911 private func panelView(_ panel: Panel) -> some View {
912 switch panel {
913 case .columns(_, let view):
914 ColumnViewSheet(view: view, run: runInColumnView, document: { session.document.map { ($0.text, $0.tree) } }) { offset in
915 commands.editor?.reveal(offset)
916 }
917 case .export(_, let source):
918 ExportSheet(source: source, inSubtree: exportSubtreeAvailable, target: exportTarget) { format, destination, open, subtree, bodyOnly in
919 export(format, to: destination, open: open, subtree: subtree, bodyOnly: bodyOnly)
920 }
921 case .plot(_, let plot):
922 PlotSheet(content: .chart(plot))
923 case .plotImage(_, let url):
924 PlotSheet(content: .image(url))
925 case .crypt(_, let request):
926 CryptSheet(request: request, text: { session.document?.text ?? "" }, apply: { applyText($0) }) { message in
927 self.panel = nil
928 if let message { commands.show(message) }
929 }
930 case .conflict:
931 ConflictSheet(session: session)
932 case .syncCopies:
933 SyncConflictSheet(session: session) { commands.show($0) }
934 case .recovery:
935 RecoverySheet(session: session) { commands.show($0) }
936 }
937 }
938
939 /// `new` in place of the buffer's text, as one edit, with the caret at `caret` or where it was.
940 private func applyText(_ new: String, caret: Int? = nil) {
941 guard let editor = commands.editor else { return }
942 let context = editor.context()
943 let caret = min(caret ?? context.caret, (new as NSString).length)
944 editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
945 }
946
947 /// `org-plot/gnuplot` for the table at the caret: through gnuplot when it's installed, as
948 /// Emacs runs it, else drawn here; written to `file:` when the options name one, else shown.
949 private func plotTable() {
950 guard let editor = commands.editor, let path = session.path else { return commands.show("No file is open") }
951 let context = editor.context()
952 let plot: TablePlot.Plot
953 do { plot = try TablePlot.plot(context.text, at: context.caret) } catch { return commands.show("\(error)") }
954 let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
955 #if !APPSTORE
956 if let gnuplot = PlotOutput.gnuplot {
957 commands.show("Plotting with gnuplot…")
958 Task {
959 do {
960 let image = try await PlotOutput.runGnuplot(plot, directory: directory, gnuplot: gnuplot)
961 if plot.options.file == nil { panel = .plotImage(UUID(), image) } else { plotWritten(image, editor: editor) }
962 } catch {
963 commands.show("\(error)")
964 }
965 }
966 return
967 }
968 #endif
969 if let url = PlotOutput.file(plot, directory: directory) {
970 guard reach([url.path]) else { return }
971 do {
972 try PlotOutput.write(plot, to: url)
973 plotWritten(url, editor: editor, note: PlotOutput.note(plot))
974 } catch {
975 commands.show("\(error)")
976 }
977 } else {
978 do { try PlotOutput.check(plot) } catch { return commands.show("\(error)") }
979 panel = .plot(UUID(), plot)
980 if let note = PlotOutput.note(plot) { commands.show(note) }
981 }
982 }
983
984 /// The image is where `file:` says; a link to it shows it again.
985 private func plotWritten(_ url: URL, editor: OrgEditor, note: String? = nil) {
986 commands.show("Plot written to \(url.lastPathComponent)" + (note.map { ". " + $0 } ?? ""))
987 if editor.showsImages { editor.refreshImages() }
988 }
989
990 /// `org-publish`, `org-publish-all`, `org-publish-current-file` and
991 /// `org-publish-current-project`, with the projects in config.toml.
992 private func publish(_ id: String) {
993 let config = (try? String(contentsOf: UserConfig.file("config.toml"), encoding: .utf8)) ?? ""
994 let loaded = Publish.projects(fromConfig: config, root: workspace.rootPaths.first)
995 if let problem = loaded.problems.first { commands.show(problem) }
996 guard !loaded.projects.isEmpty else { return commands.show("No [[publish]] projects in config.toml") }
997 let read = { (path: String) -> String? in
998 session.openDocuments.first { $0.path == path }?.document.text ?? (try? String(contentsOfFile: path, encoding: .utf8))
999 }
1000 let codeStyle = HTMLCodeStyle(highlighter: PaneView.highlighter, theme: theme)
1001 func run(_ chosen: [PublishProject], only: String? = nil) {
1002 // The chosen projects and their components read and write these folders.
1003 let involved = { loaded.projects.filter { project in chosen.contains { $0 == project || $0.components.contains(project.name) } } }
1004 guard reach(involved().flatMap { [$0.baseDirectory, $0.publishingDirectory] }, directories: true) else { return }
1005 do {
1006 let report = try Publish.publish(chosen, all: loaded.projects, only: only, read: read) { function, text, path, bodyOnly in
1007 try Publish.export(function, text: text, path: path, bodyOnly: bodyOnly, settings: Preferences.orgSettings, codeStyle: codeStyle)
1008 }
1009 commands.show("Published \(report.published.count) files" + (report.skipped.isEmpty ? "" : ", \(report.skipped.count) up to date"))
1010 } catch {
1011 commands.show("\(error)")
1012 }
1013 }
1014 let current = session.path.map { Publish.projects(containing: $0, in: loaded.projects) } ?? []
1015 switch id {
1016 case "app.publish.all":
1017 run(loaded.projects)
1018 case "app.publish.current-file":
1019 guard let path = session.path, !current.isEmpty else { return commands.show("File is not part of any known project") }
1020 run([current[0]], only: path)
1021 case "app.publish.current-project":
1022 guard !current.isEmpty else { return commands.show("File is not part of any known project") }
1023 run([current[0]])
1024 default:
1025 let names = loaded.projects.map(\.name)
1026 commands.ask(Prompt(key: "project", message: "Publish project:", choices: names)) { answer in
1027 guard let answer, let project = loaded.projects.first(where: { $0.name == answer }) else { return }
1028 run([project])
1029 }
1030 }
1031 }
1032
1033 /// Work a command hands to the platform: tables recalculated in Emacs.
1034 private func runExternal(_ request: ExternalRequest) {
1035 switch request {
1036 case .openLink(let link):
1037 if let message = LinkOpener.open(link, session: session, workspace: workspace, ask: commands.ask, elisp: runElispLink) { commands.show(message) }
1038 // `org-occur` for a regexp link, once the editor shows the file.
1039 if let regexp = Links.regexpSearch(link) {
1040 DispatchQueue.main.async { commands.editor?.perform(SparseTreeCommand(), answers: ["sparse": "/", "regexp": regexp]) }
1041 }
1042 case .tangle(let scope):
1043 guard ProAccess.shared.allows(.babel), reach(session.tangleFiles(scope)) else { return }
1044 commands.show(session.tangle(scope))
1045 case .agenda(let start, let days):
1046 commands.agendaRequest = (start, days)
1047 openWindow(id: "agenda")
1048 case .editBlock(let edit):
1049 blockEdit = BlockEditRequest(edit: edit)
1050 case .columnView(let view):
1051 panel = .columns(UUID(), view)
1052 #if APPSTORE
1053 case .emacsTable(_, _, _, let reason, _, let formula, let partial):
1054 // The fields written before the formula stay, as Emacs leaves them when a formula fails.
1055 if let partial { commands.editor?.perform(PrecomputedEdit(partial)) }
1056 if reason == TableBlocks.lockedReason {
1057 ProAccess.shared.allows(.babel)
1058 return
1059 }
1060 if let formula {
1061 commands.show(String(localized: "The table was recalculated up to \(formula), which can't be calculated here: \(TableReason.localized(reason)).", comment: "Table formulas orgstar calculated up to one it can't"))
1062 } else {
1063 commands.show(String(localized: "This table's formulas can't be calculated here: \(TableReason.localized(reason)).", comment: "Table formulas orgstar can't calculate"))
1064 }
1065 #else
1066 case .emacsTable(let table, let point, let form, let reason, let lisp, let formula, let partial):
1067 // Emacs runs the blocks `org-sbe` names without asking, so they need Babel, and
1068 // the question below each time.
1069 let blocks = reason == TableBlocks.lockedReason || session.document?.text.contains("org-sbe") == true
1070 if blocks, !ProAccess.shared.allows(.babel) {
1071 if let partial { commands.editor?.perform(PrecomputedEdit(partial)) }
1072 return
1073 }
1074 guard EmacsRunner.executable() != nil else {
1075 // Without Emacs this is the App Store build's case: keep the fields written so far.
1076 if let partial { commands.editor?.perform(PrecomputedEdit(partial)) }
1077 if let formula {
1078 return commands.show(String(localized: "The table was recalculated up to \(formula), which can't be calculated here: \(TableReason.localized(reason)).", comment: "Table formulas orgstar calculated up to one it can't"))
1079 }
1080 return commands.show(String(localized: "This table's formulas can't be calculated here: \(TableReason.localized(reason)).", comment: "Table formulas orgstar can't calculate"))
1081 }
1082 let run = {
1083 commands.show(String(localized: "Recalculating in Emacs (\(TableReason.localized(reason)))…", comment: "Table formulas sent to Emacs, and why"))
1084 commands.runInEmacs { commands.show(await session.recalculateInEmacs(table: table, point: point, form: form)) }
1085 }
1086 guard lisp, let path = session.path, let text = session.document?.text else { return run() }
1087 let content = (text as NSString).substring(with: NSRange(location: table.lowerBound, length: min((text as NSString).length, table.upperBound + 2000) - table.lowerBound))
1088 if !blocks, trust.isTrusted(path: path, content: content) { return run() }
1089 let message = blocks ? "This table's formulas run Lisp and source blocks. Run them? (yes, no)" : "This table's formulas run Lisp. Run them? (yes, no, always)"
1090 commands.ask(Prompt(key: "confirm", message: message, choices: blocks ? ["yes", "no"] : ["yes", "no", "always"])) { answer in
1091 switch answer {
1092 case "always":
1093 trust.trust(path: path, content: content)
1094 run()
1095 case "yes": run()
1096 default: commands.show("Not recalculated")
1097 }
1098 }
1099 #endif
1100 case .babel(let job):
1101 guard ProAccess.shared.allows(.babel) else { return }
1102 let run = {
1103 guard reach(session.resultFile(of: job).map { [$0] } ?? []) else { return }
1104 commands.show("Running \(job.language) block… (⌘. to cancel)")
1105 session.startBabel(job) { commands.show($0) }
1106 }
1107 guard let path = session.path else { return }
1108 if !job.alwaysAsk, trust.isTrusted(path: path, content: job.blockText) { return run() }
1109 let choices = job.alwaysAsk ? ["yes", "no"] : ["yes", "no", "always"]
1110 commands.ask(Prompt(key: "confirm", message: "Run this \(job.language) block? (\(choices.joined(separator: ", ")))", choices: choices)) { answer in
1111 switch answer {
1112 case "always":
1113 trust.trust(path: path, content: job.blockText)
1114 run()
1115 case "yes": run()
1116 default: commands.show("Not run")
1117 }
1118 }
1119 }
1120 }
1121
1122 /// Runs an `elisp:` link's form once trusted, asking as `org-link-elisp-confirm-function` does.
1123 private func runElispLink(_ form: String) {
1124 let run = { _ = Task { commands.show(await session.evaluateLink(form)) } }
1125 let content = "elisp:" + form
1126 if let path = session.path, trust.isTrusted(path: path, content: content) { return run() }
1127 let choices = session.path == nil ? ["yes", "no"] : ["yes", "no", "always"]
1128 commands.ask(Prompt(key: "confirm", message: "Execute \(form) as Elisp? (\(choices.joined(separator: ", ")))", choices: choices)) { answer in
1129 switch answer {
1130 case "always":
1131 if let path = session.path { trust.trust(path: path, content: content) }
1132 run()
1133 case "yes": run()
1134 default: commands.show("Not run")
1135 }
1136 }
1137 }
1138
1139 private struct ReminderKey: Equatable {
1140 var enabled: Bool
1141 var lead: Int
1142 var subfolders: Bool
1143 /// The widgets leave out hidden folders.
1144 var hidden: Set<String>
1145 var files: Int
1146 var changed: Int?
1147 var edits: Int
1148 var hour: Int
1149 /// The widgets' colors.
1150 var theme: ThemeSpec
1151 }
1152
1153 /// Sets the notifications for the next week's timed entries, once edits pause.
1154 private func updateReminders() async {
1155 guard let scheduler else { return }
1156 guard remindersEnabled else {
1157 await scheduler.clear()
1158 return
1159 }
1160 try? await Task.sleep(for: .seconds(2))
1161 guard !Task.isCancelled, !workspace.files.isEmpty else { return }
1162 let agenda = reminderAgenda ?? AgendaModel(workspace: workspace)
1163 reminderAgenda = agenda
1164 agenda.includeSubfolders = agendaSubfolders
1165 agenda.excludeArchives = OrgPreferences.agendaExcludeArchives()
1166 let open = session.openTexts
1167 let reminders = await agenda.reminders(open: open, lead: reminderLead)
1168 guard !Task.isCancelled else { return }
1169 await scheduler.reconcile(reminders)
1170 }
1171
1172 /// The desktop widgets' agenda and habits, written where the widget extension reads them,
1173 /// with the widgets reloaded when they changed.
1174 private func updateWidgets() async {
1175 guard !Task.isCancelled, ProAccess.shared.isUnlocked, !workspace.files.isEmpty, let file = AgendaSnapshot.file() else { return }
1176 let days = widgetAgenda ?? AgendaModel(workspace: workspace)
1177 widgetAgenda = days
1178 days.mode = .agenda(span: AgendaSnapshot.dayCount, startOffset: 0)
1179 days.startOnWeekday = nil
1180 days.includeSubfolders = agendaSubfolders
1181 days.excludeArchives = OrgPreferences.agendaExcludeArchives()
1182 days.hiddenFolders = HiddenFolders.shared.all
1183 days.agendaFiles = OrgPreferences.agendaFiles()
1184 days.options = OrgPreferences.agendaOptions(days.options)
1185 days.options.logMode = false
1186 days.calendarEvents = ProAccess.shared.isUnlocked && OrgPreferences.calendarEvents() && CalendarEvents.isAuthorized ? CalendarAccess.events : nil
1187 days.calendarNames = OrgPreferences.calendarEventCalendars()
1188 days.reminderLists = ProAccess.shared.isUnlocked && OrgPreferences.agendaReminders() && ReminderLists.isAuthorized ? CalendarAccess.reminders : nil
1189 days.reminderListNames = OrgPreferences.agendaReminderLists()
1190 let open = session.openTexts
1191 await days.refresh(open: open)
1192 guard !Task.isCancelled else { return }
1193 if (try? HabitSnapshot(habits: await days.habits(open: open), theme: theme).write()) == true {
1194 WidgetCenter.shared.reloadTimelines(ofKind: "sh.krz.orgstar.habits")
1195 }
1196 let snapshot = AgendaSnapshot(groups: days.groups(), today: days.today, theme: theme, generated: Date())
1197 if (try? snapshot.write(to: file)) == true { WidgetCenter.shared.reloadAllTimelines() }
1198 }
1199
1200 private func loadKeymap() {
1201 let loaded = KeymapLoader.load(preset, commands: Set(EditorCommands.all.map(\.id)))
1202 keymap = loaded.keymap
1203 commands.keymap = loaded.keymap
1204 commands.modal = preset.isModal
1205 if let first = loaded.problems.first {
1206 let more = loaded.problems.count > 1 ? " (and \(loaded.problems.count - 1) more)" : ""
1207 commands.show("keymap.toml: \(first)\(more)")
1208 }
1209 }
1210
1211 /// `SPC b b`: open buffers, most recent first, by name (with the folder when names repeat).
1212 private func switchBuffer() {
1213 let paths = session.recentPaths.dropFirst() + session.recentPaths.prefix(1)
1214 let labels = paths.map(session.bufferName)
1215 guard !labels.isEmpty else { return commands.show("No buffers are open") }
1216 commands.ask(Prompt(key: "buffer", message: "Switch to buffer:", choices: labels)) { answer in
1217 guard let answer, let index = labels.firstIndex(of: answer) else { return }
1218 session.open(Array(paths)[index])
1219 }
1220 }
1221
1222 /// Runs a command from a key, the palette or the Org menu.
1223 private func perform(_ id: String) {
1224 if hiddenCommandIDs.contains(id) {
1225 if let replacement = AppStoreCommands.replacement(for: id) { return perform(replacement) }
1226 return commands.show(Self.unavailable(EditorCommands.all.first { $0.id == id }?.title ?? id))
1227 }
1228 if let feature = ProFeature.required(byCommand: id), !ProAccess.shared.allows(feature) { return }
1229 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.")
1230 if orgOnly, !session.isOrg {
1231 commands.show("Not an org file")
1232 return
1233 }
1234 switch id {
1235 case "app.save":
1236 if !session.save(), session.conflict != nil { commands.showingConflict = true }
1237 case "app.quit": NSApp.terminate(nil)
1238 case "app.save-all":
1239 if !session.saveAll(), session.conflict != nil { commands.showingConflict = true }
1240 case "app.buffer.switch": switchBuffer()
1241 case "app.buffer.next": session.cycle(1)
1242 case "app.buffer.previous": session.cycle(-1)
1243 case "app.buffer.last": session.showPrevious()
1244 case "app.buffer.kill":
1245 if let window = paneWindow, window.paneCount > 1 {
1246 window.closeTab(session.path, in: window.focusedPane, commands: commands)
1247 } else if let path = session.path {
1248 if UnsavedChanges.resolve(session) { session.kill(path) }
1249 } else {
1250 NSApp.keyWindow?.performClose(nil)
1251 }
1252 case "app.buffer.kill-others":
1253 let others = session.openPaths.filter { $0 != session.path }
1254 if UnsavedChanges.resolve(session, paths: others) { others.forEach(session.kill) }
1255 case "app.buffer.kill-all":
1256 let all = session.openPaths
1257 if UnsavedChanges.resolve(session, paths: all) { all.forEach(session.kill) }
1258 case "app.toggle-tab-bar": showTabBar.toggle()
1259 case "app.split-below": paneWindow?.split(.vertical)
1260 case "app.split-right": paneWindow?.split(.horizontal)
1261 case "app.pane-close":
1262 guard let window = paneWindow, window.paneCount > 1 else { return commands.show("Attempt to delete the only pane") }
1263 commands.store.releasePane(window.focused)
1264 window.close(window.focused)
1265 focusPane(window)
1266 case "app.pane-only":
1267 guard let window = paneWindow else { return }
1268 for id in window.layout.panes where id != window.focused { commands.store.releasePane(id) }
1269 window.closeOthers()
1270 focusPane(window)
1271 case "app.pane-next":
1272 guard let window = paneWindow else { return }
1273 window.focusNext()
1274 focusPane(window)
1275 case "app.window-new": openWindow(id: "editor")
1276 case "app.babel.cancel":
1277 if session.isRunningBabel {
1278 session.cancelBabel()
1279 } else if let task = commands.emacsTask {
1280 task.cancel()
1281 } else {
1282 commands.show("Nothing is running")
1283 }
1284 case "app.toggle-outline": toggleOutline()
1285 case "app.toggle-backlinks": backlinksShown.toggle()
1286 case "app.toggle-inspector": inspectorShown.toggle()
1287 case "app.toggle-markup": showMarkup.toggle()
1288 case "app.toggle-line-numbers": showLineNumbers.toggle()
1289 case "app.import-emacs": showingImport = true
1290 case "app.edit-config": commands.jump(path: UserConfig.configFile.path, offset: 0)
1291 case "app.quick-open": commands.showingQuickOpen = true
1292 case "app.palette": commands.showingPalette = true
1293 case "app.search": commands.focusSearch = true
1294 case "app.reload-keymap":
1295 loadKeymap()
1296 commands.show("Keymap reloaded")
1297 case "app.refile", "app.refile.copy":
1298 let keep = id == "app.refile.copy"
1299 let targets = workspace.refileTargets(openPath: session.path, document: session.document)
1300 commands.ask(Prompt(key: "refile", message: keep ? "Copy to:" : "Refile to:", choices: targets.map(\.label))) { answer in
1301 guard let answer else { return }
1302 if let target = targets.first(where: { $0.label == answer }) {
1303 if let message = session.refile(to: target, keep: keep) { commands.show(message) }
1304 return
1305 }
1306 // `org-refile-allow-creating-parent-nodes`: `parent/new` adds the heading first.
1307 let creating = OrgPreferences.refileSettings().creating
1308 guard creating != .no, let (parent, child) = RefileSettings.newNode(answer, in: targets) else { return commands.show("Invalid target location") }
1309 let create = {
1310 switch session.createRefileChild(under: parent, title: child) {
1311 case .success(let target): if let message = session.refile(to: target, keep: keep) { commands.show(message) }
1312 case .failure(.message(let message)): commands.show(message)
1313 }
1314 }
1315 guard creating == .confirm else { return create() }
1316 commands.ask(Prompt(key: "confirm", message: "Create new node \"\(child)\"?", choices: ["yes", "no"])) { reply in
1317 if reply == "yes" { create() }
1318 }
1319 }
1320 case "app.refile.goto":
1321 // `C-u C-c C-w`: the target heading, or the end of a file.
1322 let targets = workspace.refileTargets(openPath: session.path, document: session.document)
1323 commands.ask(Prompt(key: "refile", message: "Goto:", choices: targets.map(\.label))) { answer in
1324 guard let answer, let target = targets.first(where: { $0.label == answer }) else { return }
1325 commands.jump(path: target.path, offset: target.start ?? Int.max)
1326 }
1327 case "app.archive":
1328 guard reach(session.archiveFile().map { [$0] } ?? []) else { return }
1329 if let message = session.archive() { commands.show(message) }
1330 case "app.table-import":
1331 // `org-table-import`: a TSV, CSV or space-separated file becomes a table at point.
1332 guard let editor = commands.editor else { return commands.show("No file is open") }
1333 let panel = NSOpenPanel()
1334 panel.allowedContentTypes = [.commaSeparatedText, .tabSeparatedText, .plainText]
1335 guard panel.runModal() == .OK, let url = panel.url else { return }
1336 guard let contents = try? String(contentsOf: url, encoding: .utf8) else { return commands.show("Can't read \(url.lastPathComponent)") }
1337 editor.perform(ImportTable(contents: contents))
1338 case "app.table-export":
1339 // `org-table-export`: CSV for a .csv name, else TSV.
1340 guard let editor = commands.editor else { return commands.show("No file is open") }
1341 let context = editor.context()
1342 guard ImportTable.exportText(context.text, at: context.caret, path: "") != nil else { return commands.show("No table at point") }
1343 let panel = NSSavePanel()
1344 panel.nameFieldStringValue = "table.csv"
1345 guard panel.runModal() == .OK, let url = panel.url,
1346 let text = ImportTable.exportText(context.text, at: context.caret, path: url.path) else { return }
1347 do {
1348 try text.write(to: url, atomically: true, encoding: .utf8)
1349 commands.show("Export done.")
1350 } catch {
1351 commands.show("File not written: \(error.localizedDescription)")
1352 }
1353 case "org.subtree.paste":
1354 guard let text = NSPasteboard.general.string(forType: .string) else { return commands.show("The clipboard is empty") }
1355 commands.editor?.perform(PasteSubtree(text: text))
1356 case "org.link.insert":
1357 commands.editor?.perform(InsertLink(stored: commands.storedLinks, file: session.path))
1358 case "org.link.store":
1359 guard let editor = commands.editor, let path = session.path else { return commands.show("No method for storing a link from this buffer") }
1360 let context = editor.context()
1361 let denote = OrgPreferences.usesDenote() ? Links.storeDenote(in: context, path: path) : nil
1362 commands.storeLink(denote ?? Links.store(in: context, path: Links.abbreviate(path, home: OrgPaths.home)))
1363 case "org.id.store-link":
1364 guard let editor = commands.editor, let path = session.path else { return }
1365 if case .commit = editor.perform(CreateID()),
1366 let link = Links.storeID(in: editor.context(), fileName: (path as NSString).lastPathComponent) {
1367 commands.storeLink(link)
1368 }
1369 case "app.agenda":
1370 openWindow(id: "agenda")
1371 case "app.clock.in":
1372 clockIn(.caret)
1373 case "app.clock.in-recent":
1374 clockIn(.select)
1375 case "app.clock.in-last":
1376 clockIn(.last)
1377 case let id where id.hasPrefix("app.clock.history."):
1378 if let index = Int(id.dropFirst("app.clock.history.".count)), index < clock.history.count { clockIn(.task(clock.history[index])) }
1379 case "app.clock.out":
1380 commands.show(clock.clockOut(session))
1381 case "app.clock.cancel":
1382 commands.show(clock.clockOut(session, cancel: true))
1383 case "app.clock.goto":
1384 let found = clock.goto(session)
1385 if let location = found.location { commands.jump(path: location.path, offset: location.offset) }
1386 if let message = found.message { commands.show(message) }
1387 case "app.clock.goto-recent":
1388 Task {
1389 let found = await clock.gotoRecent(session, ask: askClock)
1390 if let location = found.location { commands.jump(path: location.path, offset: location.offset) }
1391 if let message = found.message { commands.show(message) }
1392 }
1393 case "app.clock.default":
1394 commands.show(clock.markDefault(session))
1395 case "app.clock.resolve":
1396 Task { report(await clock.resolveOpenClocks(session, paths: orgFiles, ask: askClock)) }
1397 case "app.clock.report":
1398 openWindow(id: "clock-report")
1399 case "app.board":
1400 openWindow(id: "board")
1401 case "app.capture":
1402 NSApp.activate()
1403 openWindow(id: "capture")
1404 case "app.revert":
1405 // `:e`: the file as it is on disk; unsaved changes go to recovery.
1406 guard session.path != nil else { return commands.show("No file is open") }
1407 session.useDiskVersion()
1408 commands.show("Reverted to the file on disk")
1409 case "app.sync-conflicts":
1410 guard session.path != nil else { return commands.show("No file is open") }
1411 panel = .syncCopies(UUID())
1412 case "app.recovery":
1413 guard session.path != nil else { return commands.show("No file is open") }
1414 panel = .recovery(UUID())
1415 case "app.copy-rich-text":
1416 copyRichText()
1417 case "app.export-dialog":
1418 guard let path = session.path else { return commands.show("No file is open") }
1419 panel = .export(UUID(), URL(fileURLWithPath: path))
1420 case let id where id.hasPrefix("app.export."):
1421 export(String(id.dropFirst("app.export.".count)))
1422 case let id where id.hasPrefix("app.publish"):
1423 publish(id)
1424 case "app.plot":
1425 plotTable()
1426 case let id where id.hasPrefix("app.crypt."):
1427 crypt(id)
1428 case let id where id.hasPrefix("app.attach."):
1429 guard reach(attachActions.entry().flatMap { Attachments.directory($0, noFSCheck: true) }.map { [$0] } ?? [], directories: true) else { return }
1430 attachActions.run(id)
1431 case let id where id.hasPrefix("app.dailies.") || id.hasPrefix("app.node."):
1432 roamActions.run(id)
1433 default:
1434 if let editor = commands.editor { editor.run(id) } else { commands.show("No file is open") }
1435 }
1436 }
1437
1438 private var askClock: ClockModel.Ask { commands.askClock }
1439
1440 /// The files `org-resolve-clocks` looks through: the workspace's org files.
1441 private var orgFiles: [String] { workspace.files.filter { $0.kind == .org }.map(\.path) }
1442
1443 private func clockIn(_ target: ClockModel.Target) {
1444 Task { report(await clock.clockIn(session, target: target, paths: orgFiles, ask: askClock)) }
1445 }
1446
1447 /// The last message of a clock command, and the clock to show for `j`.
1448 private func report(_ outcome: ClockModel.Outcome) {
1449 if let jump = outcome.jump { commands.jump(path: jump.path, offset: jump.offset) }
1450 if let message = outcome.messages.last(where: { !$0.isEmpty }) { commands.show(message) }
1451 }
1452
1453 private var errorShown: Binding<Bool> {
1454 Binding(get: { workspace.lastError != nil || session.lastError != nil }, set: { _ in })
1455 }
1456}