Sources/OrgstarMobile/EditorScreen.swift
1251 lines · 64557 bytes
1#if os(iOS)
2import OrgApp
3import OrgCore
4import OrgDocument
5import PhotosUI
6import QuickLook
7import SwiftUI
8import UIKit
9import UniformTypeIdentifiers
10
11/// Editing a file: the text with Org's folding and styling, a bar of Org keys over the keyboard,
12/// and every command in a palette. The editor is the open file's live state, so autosave and
13/// merging go through the session as on the Mac.
14struct EditorScreen: View {
15 let path: String
16 let offset: Int?
17 let workspace: WorkspaceModel
18 let session: DocumentSession
19 /// The pane this screen shows its file in, from a split; nil makes one for the screen.
20 var givenPane: EditorPane? = nil
21 /// In a split, the focused pane shows the toolbar and the split the title.
22 var inSplit = false
23 var isFocused = true
24 /// Focus came to this screen's pane.
25 var onFocus: () -> Void = {}
26 /// The pane commands (`app.split-right` …), which the split runs.
27 var onPaneCommand: ((String) -> Void)? = nil
28 @State private var editor: MobileEditor?
29 /// This screen's view of the editor.
30 @State private var textView: UITextView?
31 @State private var holder = PaneHolder()
32 @Environment(\.horizontalSizeClass) private var sizeClass
33 @State private var prompt: PromptRequest?
34 @State private var message: String?
35 @State private var sheet: Sheet?
36 @State private var trust = TrustStore()
37 /// The command chosen in the palette, run once the palette is gone.
38 @State private var chosen: String?
39 @Environment(ClockModel.self) private var clock
40 @Environment(MobileModel.self) private var model
41 @Environment(\.openURL) private var openURL
42
43 /// The session's options with `buffer-file-name` and the agenda files, for clock tables.
44 private var editorOptions: EditingOptions {
45 var options = session.options
46 options.filePath = path
47 options.agendaFiles = workspace.agendaFilePaths()
48 options.denoteDirectories = DenoteNote.directories(roots: workspace.rootPaths)
49 options.denoteSequenceScheme = OrgPreferences.denoteSequenceScheme()
50 options.timer = TimerModel.shared.timer
51 return options
52 }
53
54 struct PromptRequest: Identifiable {
55 let id = UUID()
56 let prompt: Prompt
57 let reply: (String?) -> Void
58 }
59
60 /// One sheet at a time: two presenters on this screen interfere.
61 /// `org-table-import`'s file picker is up.
62 @State private var importingTable = false
63 /// The table at the caret, for `org-table-export`'s save dialog.
64 @State private var exportedTable: TableFile?
65 /// org-attach's file picker is up, for this method.
66 @State private var attaching: Attachments.Method?
67 @State private var attachingPhotos = false
68 @State private var takingPhoto = false
69 @State private var photos: [PhotosPickerItem] = []
70 /// A file shown in Quick Look.
71 @State private var previewed: URL?
72 /// The project whose publishing folder the folder picker is choosing.
73 @State private var publishFolder: PublishFolderRequest?
74 @State private var choosingPublishFolder = false
75
76 struct PublishFolderRequest {
77 let project: String
78 /// Publishes again, with the folder.
79 let then: () -> Void
80 }
81
82 enum Sheet: Identifiable {
83 case palette, conflict, syncCopies, recovery
84 /// `app.refile`, `app.refile.copy` or `app.refile.goto`.
85 case refile(String)
86 case block(BlockEdit)
87 case columns(ColumnView.View)
88 case plot(TablePlot.Plot)
89 case crypt(CryptRequest)
90 case backlinks
91 /// The subtree at this offset, to export.
92 case exportSubtree(Int)
93
94 var id: String {
95 switch self {
96 case .palette: "palette"
97 case .refile(let command): command
98 case .conflict: "conflict"
99 case .syncCopies: "syncCopies"
100 case .recovery: "recovery"
101 case .block(let edit): "block \(edit.range)"
102 case .columns: "columns"
103 case .plot: "plot"
104 case .crypt(let request): request.id.uuidString
105 case .backlinks: "backlinks"
106 case .exportSubtree: "exportSubtree"
107 }
108 }
109 }
110
111 private var pane: EditorPane? { givenPane ?? holder.pane }
112
113 /// The pane commands, as the Mac's View menu has them.
114 static let paneCommands = ["app.split-right", "app.split-below", "app.pane-next", "app.pane-close", "app.pane-only"]
115
116 var body: some View {
117 Group {
118 if let editor, let textView {
119 EditorTextView(editor: editor, view: textView, palette: { sheet = .palette })
120 .ignoresSafeArea(.container, edges: .bottom)
121 } else {
122 ProgressView()
123 }
124 }
125 .modifier(EditorTitle(title: session.bufferName(path) + (session.dirtyPaths.contains(path) ? " •" : ""), shown: !inSplit))
126 .toolbar(.hidden, for: .tabBar)
127 .toolbar {
128 if !inSplit || isFocused {
129 ToolbarItemGroup(placement: .primaryAction) {
130 if pane?.conflict != nil {
131 Button("Conflict", systemImage: "exclamationmark.triangle") { sheet = .conflict }
132 }
133 Button("Undo", systemImage: "arrow.uturn.backward") { editor?.run("edit.undo") }
134 Menu("More", systemImage: "ellipsis.circle") {
135 Button("Commands", systemImage: "command") { sheet = .palette }
136 Button("Word Count", systemImage: "textformat.123") { message = wordCount() }
137 Button("Clock In", systemImage: "stopwatch") { editor?.run("app.clock.in") }
138 Button("Column View", systemImage: "tablecells") { editor?.run("org.columns") }
139 Button("Column View of File", systemImage: "tablecells.badge.ellipsis") { editor?.run("org.columns.global") }
140 Menu("Table", systemImage: "tablecells") {
141 Button("Import Table from File…", systemImage: "square.and.arrow.down") { importingTable = true }
142 Button("Export Table as CSV…", systemImage: "square.and.arrow.up") { exportTable(csv: true) }
143 Button("Export Table as TSV…", systemImage: "square.and.arrow.up") { exportTable(csv: false) }
144 Button("Plot Table", systemImage: "chart.xyaxis.line") { plotTable() }
145 }
146 Toggle(isOn: Binding(get: { model.showMarkup }, set: { model.showMarkup = $0 })) {
147 Label("Show Markup", systemImage: "chevron.left.forwardslash.chevron.right")
148 }
149 RecentClockMenu(clock: clock) { editor?.run($0) }
150 Button("Backlinks", systemImage: "arrow.uturn.backward.circle") { if ProAccess.shared.allows(.roam) { sheet = .backlinks } }
151 Menu("Daily Notes", systemImage: "calendar") {
152 Button("Today", systemImage: "calendar") { roam("app.dailies.today") }
153 Button("Yesterday", systemImage: "chevron.backward") { roam("app.dailies.yesterday") }
154 Button("Tomorrow", systemImage: "chevron.forward") { roam("app.dailies.tomorrow") }
155 Button("Date…", systemImage: "calendar.badge.clock") { roam("app.dailies.date") }
156 Button("Capture to Today", systemImage: "square.and.pencil") { roam("app.dailies.capture-today") }
157 Button("Previous Daily Note", systemImage: "arrow.left") { roam("app.dailies.previous") }
158 Button("Next Daily Note", systemImage: "arrow.right") { roam("app.dailies.next") }
159 }
160 Button("Find Node…", systemImage: "point.3.connected.trianglepath.dotted") { roam("app.node.find") }
161 Button("Insert Node Link…", systemImage: "link") { roam("app.node.insert") }
162 Menu("Attachments", systemImage: "paperclip") {
163 Button("Attach File…", systemImage: "doc.badge.plus") { attaching = .cp }
164 Button("Attach Photo or Video…", systemImage: "photo.badge.plus") { attachingPhotos = true }
165 if CameraPicker.isAvailable {
166 Button("Take Photo…", systemImage: "camera") { takingPhoto = true }
167 }
168 Button("Attach File from URL…", systemImage: "link.badge.plus") { attachActions.run("app.attach.url") }
169 Button("New Attachment…", systemImage: "square.and.pencil") { attachActions.run("app.attach.new") }
170 Button("Open Attachment…", systemImage: "paperclip") { attachActions.run("app.attach.open") }
171 Button("Show Attachment Folder", systemImage: "folder") { attachActions.run("app.attach.reveal") }
172 Button("Delete Attachment…", systemImage: "trash") { attachActions.run("app.attach.delete") }
173 Button("Delete All Attachments…", systemImage: "trash.slash") { attachActions.run("app.attach.delete-all") }
174 Button("Sync Attachments", systemImage: "arrow.triangle.2.circlepath") { attachActions.run("app.attach.sync") }
175 Button("Set Attachment Folder…", systemImage: "folder.badge.gearshape") { attachActions.run("app.attach.set-directory") }
176 Button("Unset Attachment Folder", systemImage: "folder.badge.minus") { attachActions.run("app.attach.unset-directory") }
177 }
178 Menu("Encryption", systemImage: "lock") {
179 Button("Encrypt Entry…", systemImage: "lock") { crypt("app.crypt.encrypt-entry") }
180 Button("Decrypt Entry…", systemImage: "lock.open") { crypt("app.crypt.open-entry") }
181 Button("Decrypt Entry in File…", systemImage: "lock.open.trianglebadge.exclamationmark") { crypt("app.crypt.decrypt-entry") }
182 Button("Encrypt Tagged Entries…", systemImage: "lock.rectangle.stack") { crypt("app.crypt.encrypt-entries") }
183 Button("Forget Encryption Passphrase", systemImage: "key.slash") { crypt("app.crypt.forget-passphrase") }
184 }
185 if let text = session.document(of: path)?.text {
186 ExportMenu(path: path, text: text, report: { message = $0 }, exportSubtree: exportSubtree)
187 }
188 Button("Sync Conflict Copies", systemImage: "doc.on.doc") { sheet = .syncCopies }
189 Button("Recovered Versions", systemImage: "clock.arrow.circlepath") { sheet = .recovery }
190 if onPaneCommand != nil, sizeClass == .regular {
191 Menu("Panes", systemImage: "rectangle.split.2x1") {
192 Button("Split Pane Right", systemImage: "rectangle.split.2x1") { onPaneCommand?("app.split-right") }
193 Button("Split Pane Below", systemImage: "rectangle.split.1x2") { onPaneCommand?("app.split-below") }
194 if inSplit {
195 Button("Next Pane", systemImage: "arrow.right.square") { onPaneCommand?("app.pane-next") }
196 Button("Close Pane", systemImage: "xmark.square") { onPaneCommand?("app.pane-close") }
197 Button("Close Other Panes", systemImage: "square") { onPaneCommand?("app.pane-only") }
198 }
199 }
200 }
201 }
202 }
203 }
204 }
205 .safeAreaInset(edge: .top) {
206 VStack(spacing: 0) {
207 if let timer = TimerModel.shared.timer {
208 TimelineView(.periodic(from: .now, by: 1)) { context in
209 Text(timer.modeLine(now: context.date)).font(.callout.monospacedDigit())
210 }
211 .frame(maxWidth: .infinity).padding(4).background(.bar)
212 }
213 if let message {
214 Text(message).font(.callout).padding(8).frame(maxWidth: .infinity).background(.bar)
215 .onTapGesture { self.message = nil }
216 .task(id: message) {
217 try? await Task.sleep(for: .seconds(4))
218 if self.message == message { self.message = nil }
219 }
220 }
221 }
222 }
223 .sheet(item: $prompt) { request in
224 PromptSheet(prompt: request.prompt) { answer in
225 prompt = nil
226 request.reply(answer)
227 }
228 }
229 .sheet(item: $sheet, onDismiss: {
230 // After the sheet has gone, so a command's own prompt can show.
231 if let id = chosen {
232 chosen = nil
233 editor?.run(id)
234 }
235 }) { sheet in
236 switch sheet {
237 case .palette: if let editor { CommandPalette(editor: editor, panes: onPaneCommand != nil && sizeClass == .regular, split: inSplit) { chosen = $0 } }
238 case .conflict: ConflictSheet(session: session)
239 case .syncCopies: SyncConflictSheet(session: session) { message = $0 }
240 case .recovery: RecoverySheet(session: session) { message = $0 }
241 case .refile(let command):
242 RefileSheet(targets: workspace.refileTargets(openPath: session.path, document: session.document),
243 create: command == "app.refile.goto" || OrgPreferences.refileSettings().creating == .no ? nil : { parent, child in
244 self.sheet = nil
245 switch session.createRefileChild(under: parent, title: child) {
246 case .success(let target):
247 guard let path = session.path, let editor else { return }
248 message = session.refile(to: target, from: (path, editor.editContext().caret), keep: command == "app.refile.copy")
249 case .failure(.message(let text)): message = text
250 }
251 }) { target in
252 self.sheet = nil
253 guard let target else { return }
254 if command == "app.refile.goto" {
255 model.openRequest = .offset(target.path, target.start ?? Int.max)
256 } else {
257 refile(to: target, keep: command == "app.refile.copy")
258 }
259 }
260 case .block(let edit):
261 BlockEditSheet(edit: edit, theme: MobileTheme(model.theme)) { content in
262 self.sheet = nil
263 if let content, let editor { _ = editor.perform(ReplaceBlockLines(edit: edit, content: content)) }
264 }
265 case .columns(let view):
266 ColumnViewScreen(view: view, session: session, path: path) { offset in editor?.reveal(offset) }
267 case .plot(let plot):
268 PlotScreen(plot: plot)
269 case .crypt(let request):
270 CryptScreen(request: request, session: session, editor: editor) { message = $0 }
271 case .exportSubtree(let caret):
272 if let text = session.document(of: path)?.text { SubtreeExportScreen(path: path, text: text, caret: caret) }
273 case .backlinks:
274 BacklinksScreen(workspace: workspace, session: session, path: path, caret: editor?.editContext().caret ?? 0) { location in
275 if location.path == path { editor?.reveal(location.start) } else { model.openRequest = .heading(location) }
276 }
277 }
278 }
279 .fileImporter(isPresented: $importingTable, allowedContentTypes: [.commaSeparatedText, .tabSeparatedText, .plainText]) { result in
280 importTable(result)
281 }
282 .background {
283 // A second importer on the same view would replace the first.
284 Color.clear.fileImporter(isPresented: Binding(get: { attaching != nil }, set: { if !$0 { attaching = nil } }),
285 allowedContentTypes: [.item, .folder], allowsMultipleSelection: true) { result in
286 let method = attaching ?? .cp
287 switch result {
288 case .success(let urls): attachActions.attach(urls, method: method)
289 case .failure(let error): message = error.localizedDescription
290 }
291 }
292 }
293 .background {
294 Color.clear.fileImporter(isPresented: $choosingPublishFolder, allowedContentTypes: [.folder]) { result in
295 guard let request = publishFolder else { return }
296 publishFolder = nil
297 switch result {
298 case .success(let url):
299 if !PublishFolders.shared.set(url, for: request.project) { message = "orgstar can use \(url.lastPathComponent) only until it quits" }
300 request.then()
301 case .failure(let error): message = error.localizedDescription
302 }
303 }
304 }
305 .photosPicker(isPresented: $attachingPhotos, selection: $photos, matching: .any(of: [.images, .videos]))
306 .fullScreenCover(isPresented: $takingPhoto) {
307 CameraPicker { data in
308 takingPhoto = false
309 if let data { attachActions.yankImage(data, ext: "jpg", prefix: "photo") }
310 }
311 .ignoresSafeArea()
312 }
313 .onChange(of: photos) { _, items in
314 guard !items.isEmpty else { return }
315 photos = []
316 attachPhotos(items)
317 }
318 .quickLookPreview($previewed)
319 .fileExporter(isPresented: Binding(get: { exportedTable != nil }, set: { if !$0 { exportedTable = nil } }),
320 document: exportedTable, contentType: exportedTable?.type ?? .commaSeparatedText,
321 defaultFilename: exportedTable?.type == .tabSeparatedText ? "table.tsv" : "table.csv") { result in
322 if case .failure(let error) = result { message = error.localizedDescription } else { message = "Export done." }
323 }
324 .onChange(of: pane?.conflict) { _, conflict in
325 if conflict != nil, isFocused { sheet = .conflict }
326 }
327 .onChange(of: session.lastError) { _, error in
328 if let error { message = error; session.lastError = nil }
329 }
330 .onReceive(NotificationCenter.default.publisher(for: OrgExport.refused)) { message = $0.object as? String }
331 .onAppear(perform: start)
332 // A pane command moved focus here.
333 .onChange(of: isFocused) {
334 guard isFocused, let textView, !textView.isFirstResponder else { return }
335 editor?.focus(textView)
336 textView.becomeFirstResponder()
337 }
338 .onChange(of: pane?.revealRequest?.id) {
339 if let offset = pane?.revealRequest?.offset, pane?.path == path { editor?.reveal(offset) }
340 }
341 .onChange(of: model.settingsVersion) {
342 editor?.options = editorOptions
343 editor?.themeSpec = model.theme
344 editor?.keymap = model.keymap
345 editor?.modal = model.modalKeys
346 }
347 .onChange(of: model.showMarkup) { editor?.showMarkup = model.showMarkup }
348 .onChange(of: TimerModel.shared.timer) { editor?.options = editorOptions }
349 .onDisappear {
350 // Typing the reader shows next, and a save, don't wait for the autosave delay.
351 if session.dirtyPaths.contains(path) { _ = session.save(path) }
352 }
353 }
354
355 /// Store Link, Store ID Link and Insert Link, with the links stored while the app runs.
356 private func link(_ id: String) {
357 guard let editor else { return }
358 switch id {
359 case "org.link.store":
360 let context = editor.editContext()
361 let denote = OrgPreferences.usesDenote() ? Links.storeDenote(in: context, path: path) : nil
362 message = StoredLink.add(denote ?? Links.store(in: context, path: Links.abbreviate(path, home: OrgPaths.home)), to: &model.storedLinks)
363 case "org.id.store-link":
364 if case .commit = editor.perform(CreateID()),
365 let link = Links.storeID(in: editor.editContext(), fileName: (path as NSString).lastPathComponent) {
366 message = StoredLink.add(link, to: &model.storedLinks)
367 }
368 default:
369 _ = editor.perform(InsertLink(stored: model.storedLinks, file: path))
370 }
371 }
372
373 /// Runs a block once it's trusted, asking as `org-confirm-babel-evaluate` does.
374 private func run(_ job: BabelJob) {
375 let go = {
376 message = "Running \(job.language) block…"
377 session.startBabel(job) { message = $0 }
378 }
379 if !job.alwaysAsk, trust.isTrusted(path: path, content: job.blockText) { return go() }
380 let choices = job.alwaysAsk ? ["yes", "no"] : ["yes", "no", "always"]
381 prompt = PromptRequest(prompt: Prompt(key: "confirm", message: "Run this \(job.language) block?", choices: choices)) { answer in
382 switch answer {
383 case "always":
384 trust.trust(path: path, content: job.blockText)
385 go()
386 case "yes": go()
387 default: message = "Not run"
388 }
389 }
390 }
391
392 private func start() {
393 let pane: EditorPane
394 if let existing = self.pane {
395 pane = existing
396 } else {
397 pane = session.makePane()
398 holder.pane = pane
399 let store = model.editors, path = path
400 holder.release = { [weak session] in
401 store.release(pane.id, path: path)
402 session?.closePane(pane)
403 }
404 }
405 if pane.path != path { session.open(path, in: pane) }
406 model.editors.prune(session)
407 guard let editor = model.editors.editor(for: path, session: session, make: makeEditor) else { return }
408 let view = model.editors.view(for: pane.id, of: editor)
409 editor.onFocus[ObjectIdentifier(view)] = { [weak session] in
410 session?.focused = pane
411 bind(editor)
412 onFocus()
413 }
414 // A pane a split adds leaves focus where it was, as `split-window` does.
415 if isFocused {
416 session.focused = pane
417 bind(editor)
418 editor.focus(view)
419 }
420 self.editor = editor
421 textView = view
422 if let offset { editor.reveal(offset) }
423 if pane.conflict != nil {
424 sheet = .conflict
425 } else if case let copies = session.syncConflictCopies().count, copies > 0 {
426 message = "\(copies) sync conflict \(copies == 1 ? "copy" : "copies") of this file; More › Sync Conflict Copies compares them."
427 }
428 }
429
430 private func makeEditor() -> MobileEditor? {
431 guard let document = session.document(of: path) else { return nil }
432 let editor = MobileEditor(
433 document: document, editable: document.isEditable, options: editorOptions, theme: model.theme,
434 showMarkup: model.showMarkup, baseDirectory: URL(fileURLWithPath: path).deletingLastPathComponent()
435 )
436 let path = path
437 editor.attachmentPath = { DocumentSession.attachmentPath($0, at: $1, tree: $2, path: path) }
438 return editor
439 }
440
441 /// The editor's callbacks go to this screen: it's shown here, or its view here took focus.
442 private func bind(_ editor: MobileEditor) {
443 editor.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] }
444 editor.onChange = { [weak session] in session?.bufferChanged(path) }
445 editor.onMessage = { message = $0 }
446 editor.onPrompt = { prompt, reply in self.prompt = PromptRequest(prompt: prompt, reply: reply) }
447 editor.onLink = { link in follow(link) }
448 editor.onEditBlock = { edit in sheet = .block(edit) }
449 editor.onColumnView = { view in sheet = .columns(view) }
450 editor.onTangle = { scope in if ProAccess.shared.allows(.babel) { message = session.tangle(scope) } }
451 editor.onBabel = { job in if ProAccess.shared.allows(.babel) { run(job) } }
452 editor.onRefreshSetup = { session.refreshSetup() }
453 editor.onAgenda = { start, count in model.agendaRequest = .init(start: start, count: count) }
454 editor.keymap = model.keymap
455 editor.modal = model.modalKeys
456 // Dropped files are copies the drop made, so they are attached, not linked or opened.
457 editor.onFiles = { attachActions.drop($0, method: .attach, attachMethod: .mv) }
458 editor.onImage = { attachActions.yankImage($0, ext: $1) }
459 editor.onAppCommand = { id in
460 if let feature = ProFeature.required(byCommand: id), !ProAccess.shared.allows(feature) { return }
461 if Self.paneCommands.contains(id) {
462 if let onPaneCommand { onPaneCommand(id) } else { message = "Not available here" }
463 } else if id == "app.save" {
464 _ = session.save(path)
465 } else if id == "app.archive" {
466 if let caret = self.editor?.editContext().caret { message = session.archive(from: (path, caret)) }
467 } else if id == "app.copy-rich-text" {
468 if let text = session.document(of: path)?.text { message = ExportMenu.copy(path: path, text: text, theme: model.theme) }
469 } else if id == "app.export.html-open" {
470 exportHTMLAndOpen()
471 } else if id == "app.export.icalendar-agenda" || id == "app.export.icalendar-combined" {
472 agendaCalendars(combined: id == "app.export.icalendar-combined")
473 } else if id.hasPrefix("app.publish") {
474 publish(id)
475 } else if AppStoreCommands.unavailable(id) {
476 message = "Attachments can't be linked on iPhone and iPad; Attach File… copies the file."
477 } else if ["app.refile", "app.refile.copy", "app.refile.goto"].contains(id) {
478 sheet = .refile(id)
479 } else if id == "app.table-import" {
480 importingTable = true
481 } else if id == "app.table-export" {
482 exportTable(csv: true)
483 } else if id == "app.plot" {
484 plotTable()
485 } else if id.hasPrefix("app.crypt.") {
486 crypt(id)
487 } else if id.hasPrefix("app.attach.") {
488 attachActions.run(id)
489 } else if id.hasPrefix("app.dailies.") || id.hasPrefix("app.node.") {
490 roamActions.run(id)
491 } else if id == "app.backlinks" {
492 sheet = .backlinks
493 } else if id == "app.toggle-markup" {
494 model.showMarkup.toggle()
495 } else if MobileEditor.linkCommands.contains(id) {
496 link(id)
497 } else if !MobileClock.run(id, model: model, workspace: workspace, show: { message = $0 }) {
498 message = "Not available on iOS yet"
499 }
500 }
501 }
502}
503
504extension EditorScreen {
505 /// Follows a link; files the editor doesn't open show in Quick Look.
506 private func follow(_ link: OrgLink) {
507 switch session.follow(link, workspace: workspace, isText: { _ in false }) {
508 case .shown:
509 // A link to another file shows it on its own screen; this pane keeps its file.
510 guard let pane, let target = pane.path, target != path else { message = nil; return }
511 let caret = session.caret(of: target) ?? 0
512 session.open(path, in: pane)
513 model.openRequest = .offset(target, caret)
514 case .openExternally(let url): if url.isFileURL { previewed = url } else { openURL(url) }
515 case .message(let text): message = text
516 case .choose(let question, let paths):
517 let labels = paths.map { ($0 as NSString).lastPathComponent }
518 prompt = PromptRequest(prompt: Prompt(key: "file", message: question, choices: labels)) { answer in
519 guard let answer, let index = labels.firstIndex(of: answer) else { return }
520 follow(OrgLink(type: "file", path: paths[index], raw: "file:" + paths[index]))
521 }
522 case .elisp(let form):
523 // Once trusted, as `org-link-elisp-confirm-function` asks.
524 let go = { _ = Task { message = await session.evaluateLink(form) } }
525 let content = "elisp:" + form
526 if trust.isTrusted(path: path, content: content) { return go() }
527 prompt = PromptRequest(prompt: Prompt(key: "confirm", message: "Execute \(form) as Elisp?", choices: ["yes", "no", "always"])) { answer in
528 switch answer {
529 case "always":
530 trust.trust(path: path, content: content)
531 go()
532 case "yes": go()
533 default: message = "Not run"
534 }
535 }
536 }
537 }
538
539 /// org-roam's daily notes and nodes.
540 private var roamActions: RoamActions {
541 RoamActions(
542 session: session, roots: { workspace.rootPaths },
543 nodes: { workspace.nodes(overlay: workspace.overlay(session.openDocuments)) },
544 show: { message = $0 }, ask: { prompt = PromptRequest(prompt: $0, reply: $1) },
545 open: { file, offset in
546 if file == path { editor?.reveal(offset) } else { model.openRequest = .offset(file, offset) }
547 },
548 insertLink: { link, title in
549 guard let editor else { return }
550 let context = editor.editContext()
551 let range = context.selection.first ?? context.caret..<context.caret
552 let selected = (context.text as NSString).substring(with: NSRange(range))
553 let text = Links.makeString(link, selected.isEmpty ? title : selected)
554 let end = range.lowerBound + (text as NSString).length
555 _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: [TextEdit(range: range, replacement: text)], selection: [end..<end])))
556 },
557 refresh: { Task { await workspace.refresh() } })
558 }
559
560 /// org-attach's commands for the entry at the caret.
561 private var attachActions: AttachActions {
562 AttachActions(
563 entry: {
564 guard let editor else { return nil }
565 let context = editor.editContext()
566 return Attachments.Entry(text: context.text, offset: context.caret, path: path, options: context.options)
567 },
568 apply: { new, caret in
569 guard let editor else { return }
570 let context = editor.editContext()
571 let caret = min(caret ?? context.caret, (new as NSString).length)
572 _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
573 },
574 show: { message = $0 },
575 ask: { prompt = PromptRequest(prompt: $0, reply: $1) },
576 storeLink: { _ = StoredLink.add($0, to: &model.storedLinks) },
577 open: { follow(OrgLink(type: "file", path: $0, raw: "file:" + $0)) },
578 reveal: { dir in
579 if let url = URL(string: "shareddocuments://" + (dir.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? dir)) { openURL(url) }
580 },
581 pick: { attaching = $0 })
582 }
583
584 /// Photos and videos attached under the names Photos gives them, linked at the caret.
585 private func attachPhotos(_ items: [PhotosPickerItem]) {
586 Task { @MainActor in
587 var urls: [URL] = []
588 for item in items {
589 if let picked = try? await item.loadTransferable(type: PickedFile.self) { urls.append(picked.url) }
590 }
591 if urls.count < items.count { message = "Can't read \(items.count - urls.count) of the items" }
592 if !urls.isEmpty { attachActions.drop(urls, method: .attach, attachMethod: .mv) }
593 }
594 }
595
596 /// `org-table-import`: a TSV, CSV or space-separated file becomes a table at the caret.
597 private func importTable(_ result: Result<URL, Error>) {
598 guard case .success(let url) = result, let editor else { return }
599 let scoped = url.startAccessingSecurityScopedResource()
600 defer { if scoped { url.stopAccessingSecurityScopedResource() } }
601 guard let contents = try? String(contentsOf: url, encoding: .utf8) else { return message = "Can't read \(url.lastPathComponent)" }
602 _ = editor.perform(ImportTable(contents: contents))
603 }
604
605 /// The export formats for the subtree at the caret, as the Mac's export sheet's scope.
606 private func exportSubtree() {
607 guard let context = editor?.editContext() else { return }
608 guard ExportScope.subtree(context.text, at: context.caret) != nil else { return message = "Not in a subtree" }
609 sheet = .exportSubtree(context.caret)
610 }
611
612 /// `org-html-export-to-html` and open: the page in Quick Look, from a temporary file.
613 private func exportHTMLAndOpen() {
614 guard let text = session.document(of: path)?.text else { return }
615 let html = OrgExport.html(text, path: path, theme: model.theme)
616 let name = ExportScope.output(for: URL(fileURLWithPath: path), name: ExportScope.fileName(text, settings: OrgPreferences.orgSettings()), extension: "html")
617 .lastPathComponent
618 do {
619 previewed = try HTMLPreview.write(html, directory: URL(fileURLWithPath: path).deletingLastPathComponent(), name: name)
620 } catch {
621 message = "Can't export \(name): \(error.localizedDescription)"
622 }
623 }
624
625 /// The agenda files' calendars written beside them, or combined in one shown in Quick Look,
626 /// whose share button saves or sends it.
627 private func agendaCalendars(combined: Bool) {
628 guard let calendars = AgendaCalendars(model: model) else { return message = "No agenda files" }
629 guard combined else { return message = calendars.exportEach() }
630 do {
631 previewed = try calendars.combined()
632 } catch {
633 message = "Can't export: \(error.localizedDescription)"
634 }
635 }
636
637 /// `org-publish` and its variants, for the `[[publish]]` projects in config.toml.
638 private func publish(_ id: String) {
639 guard let all = publishProjects() else { return }
640 let current = Publish.projects(containing: path, in: all)
641 switch id {
642 case "app.publish.all":
643 publish(all.map(\.name))
644 case "app.publish.current-file":
645 guard let project = current.first else { return message = "File is not part of any known project" }
646 publish([project.name], only: path)
647 case "app.publish.current-project":
648 guard let project = current.first else { return message = "File is not part of any known project" }
649 publish([project.name])
650 default:
651 prompt = PromptRequest(prompt: Prompt(key: "project", message: "Publish project:", choices: all.map(\.name))) { answer in
652 if let answer, all.contains(where: { $0.name == answer }) { publish([answer]) }
653 }
654 }
655 }
656
657 /// The projects in config.toml, each publishing to the folder chosen for it; nil, with a
658 /// message, when there are none.
659 private func publishProjects() -> [PublishProject]? {
660 let config = (try? String(contentsOf: UserConfig.file("config.toml"), encoding: .utf8)) ?? ""
661 let loaded = Publish.projects(fromConfig: config, root: workspace.rootPaths.first)
662 if let problem = loaded.problems.first { message = problem }
663 guard !loaded.projects.isEmpty else {
664 message = "No [[publish]] projects in config.toml"
665 return nil
666 }
667 return PublishFolders.shared.applied(to: loaded.projects)
668 }
669
670 /// Publishes the projects named, `only` that file when given. A project that publishes
671 /// outside the folders added to orgstar asks for its folder first, once.
672 private func publish(_ names: [String], only: String? = nil) {
673 guard let all = publishProjects() else { return }
674 let chosen = all.filter { names.contains($0.name) }
675 do {
676 if let project = try PublishFolders.shared.needed(chosen, all: all, roots: workspace.rootPaths).first {
677 message = "Choose the folder \(project.name) publishes to"
678 publishFolder = PublishFolderRequest(project: project.name) { publish(names, only: only) }
679 choosingPublishFolder = true
680 return
681 }
682 if let project = try Publish.expand(chosen, all: all).first(where: { !FileManager.default.fileExists(atPath: $0.baseDirectory) }) {
683 return message = "Can't read \(project.name)'s base-directory, \(OrgPaths.abbreviatingWithTilde(project.baseDirectory))"
684 }
685 let read = { (file: String) -> String? in
686 session.openDocuments.first { $0.path == file }?.document.text ?? (try? String(contentsOfFile: file, encoding: .utf8))
687 }
688 let codeStyle = HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme)
689 // As the Export menu: no author unless the file has #+AUTHOR:.
690 let report = try Publish.publish(chosen, all: all, only: only, author: "", read: read) { function, text, file, bodyOnly in
691 try Publish.export(function, text: text, path: file, bodyOnly: bodyOnly, settings: OrgPreferences.orgSettings(), codeStyle: codeStyle, author: "")
692 }
693 message = "Published \(report.published.count) files" + (report.skipped.isEmpty ? "" : ", \(report.skipped.count) up to date")
694 } catch {
695 message = "\(error)"
696 }
697 }
698
699 /// Org-roam's commands, with Pro.
700 private func roam(_ id: String) {
701 if ProAccess.shared.allows(.roam) { roamActions.run(id) }
702 }
703
704 /// org-crypt's commands at the caret, through the passphrase sheet.
705 private func crypt(_ id: String) {
706 if let feature = ProFeature.required(byCommand: id), !ProAccess.shared.allows(feature) { return }
707 guard let editor else { return }
708 let context = editor.editContext()
709 switch id {
710 case "app.crypt.forget-passphrase":
711 CryptPassphrases.forget(path)
712 message = "Passphrase forgotten for \((path as NSString).lastPathComponent)"
713 case "app.crypt.encrypt-entries":
714 sheet = .crypt(CryptRequest(mode: .encryptAll(tag: OrgPreferences.cryptTag()), path: path, offset: context.caret))
715 default:
716 guard OrgCrypt.heading(context.text, at: context.caret) != nil else { return message = "Before first headline" }
717 let encrypted = OrgCrypt.encryptedRange(context.text, at: context.caret) != nil
718 if id == "app.crypt.encrypt-entry" {
719 guard !encrypted else { return message = "The entry is encrypted already" }
720 sheet = .crypt(CryptRequest(mode: .encrypt, path: path, offset: context.caret))
721 } else {
722 guard encrypted else { return message = "Not an encrypted entry" }
723 sheet = .crypt(CryptRequest(mode: id == "app.crypt.open-entry" ? .open : .decryptInPlace, path: path, offset: context.caret))
724 }
725 }
726 }
727
728 /// `org-plot/gnuplot`, drawn by Swift Charts: written to `file:` when the options name
729 /// one, else shown.
730 private func plotTable() {
731 guard let editor else { return }
732 let context = editor.editContext()
733 do {
734 let plot = try TablePlot.plot(context.text, at: context.caret)
735 if let url = PlotOutput.file(plot, directory: URL(fileURLWithPath: path).deletingLastPathComponent()) {
736 try PlotOutput.write(plot, to: url)
737 message = "Plot written to \(url.lastPathComponent)" + (PlotOutput.note(plot).map { ". " + $0 } ?? "")
738 if editor.showsImages { editor.restyleAll() }
739 } else {
740 try PlotOutput.check(plot)
741 sheet = .plot(plot)
742 if let note = PlotOutput.note(plot) { message = note }
743 }
744 } catch {
745 message = "\(error)"
746 }
747 }
748
749 /// `org-table-export` of the table at the caret, as CSV or TSV.
750 /// Words, characters and reading time of the selection, or of the file.
751 private func wordCount() -> String {
752 guard let editor else { return "No file is open" }
753 let text = editor.document.text as NSString
754 let selection = editor.textView.selectedRange
755 let selected = selection.length > 0 && NSMaxRange(selection) <= text.length
756 let counts = TextStats.region(selected ? text.substring(with: selection) : text as String)
757 return (selected ? "Selection: " : "") + TextStats.summary(words: counts.words, characters: counts.characters)
758 }
759
760 private func exportTable(csv: Bool) {
761 guard let editor else { return }
762 let context = editor.editContext()
763 guard let text = ImportTable.exportText(context.text, at: context.caret, path: csv ? "table.csv" : "table.tsv") else {
764 return message = "No table at point"
765 }
766 exportedTable = TableFile(text: text, type: csv ? .commaSeparatedText : .tabSeparatedText)
767 }
768
769 /// `org-refile` of the entry at the caret, to a target worked out again from the files
770 /// now, as the agenda's Refile… does.
771 func refile(to target: RefileTarget, keep: Bool = false) {
772 guard let editor, let path = session.path else { return }
773 let caret = editor.editContext().caret
774 guard let current = workspace.refileTargets(openPath: path, document: session.document).first(where: { $0.label == target.label }) else {
775 message = "Can't find \(target.label) any more."
776 return
777 }
778 message = session.refile(to: current, from: (path, caret), keep: keep)
779 }
780}
781
782/// The editor's text view, with the Org key bar over the keyboard.
783struct EditorTextView: UIViewRepresentable {
784 let editor: MobileEditor
785 /// This pane's view of the editor.
786 let view: UITextView
787 let palette: () -> Void
788
789 func makeUIView(context: Context) -> UITextView {
790 let bar = UIHostingController(rootView: KeyBar(editor: editor, palette: palette))
791 bar.view.frame = CGRect(x: 0, y: 0, width: 400, height: 48)
792 bar.view.backgroundColor = .clear
793 bar.sizingOptions = []
794 view.inputAccessoryView = bar.view
795 context.coordinator.bar = bar
796 return view
797 }
798
799 func updateUIView(_ view: UITextView, context: Context) {}
800
801 func makeCoordinator() -> Coordinator { Coordinator() }
802
803 final class Coordinator {
804 var bar: UIViewController?
805 }
806}
807
808/// Org's keys for a touch keyboard: each button does what its key does at the caret, as the
809/// Emacs keymap binds it (M-→ demotes a heading, indents an item, moves a table column).
810struct KeyBar: View {
811 let editor: MobileEditor
812 let palette: () -> Void
813
814 private static let keys: [(label: String, symbol: String?, keys: String)] = [
815 ("Fold", "arrow.right.to.line", "TAB"),
816 ("Overview", "arrow.left.to.line", "S-TAB"),
817 ("Promote", "decrease.indent", "M-<left>"),
818 ("Demote", "increase.indent", "M-<right>"),
819 ("Move up", "arrow.up.square", "M-<up>"),
820 ("Move down", "arrow.down.square", "M-<down>"),
821 ("New heading or item", "plus", "M-RET"),
822 ("TODO", nil, "C-c C-t"),
823 ("Act at point", "checkmark.square", "C-c C-c"),
824 ("Schedule", "calendar", "C-c C-s"),
825 ("Deadline", "calendar.badge.exclamationmark", "C-c C-d"),
826 ("Tags", "tag", "C-c C-q"),
827 ("Open link", "link", "C-c C-o"),
828 ]
829
830 /// Emphasis for the selection, or a pair of markers with the caret between.
831 private static let emphasis: [(label: String, symbol: String, command: String)] = [
832 ("Bold", "bold", "org.emphasize.bold"),
833 ("Italic", "italic", "org.emphasize.italic"),
834 ("Code", "chevron.left.forwardslash.chevron.right", "org.emphasize.code"),
835 ]
836
837 var body: some View {
838 ScrollView(.horizontal, showsIndicators: false) {
839 HStack(spacing: 4) {
840 Button("Commands", systemImage: "command", action: palette)
841 ForEach(Self.keys, id: \.keys) { key in
842 Button {
843 editor.run(keys: key.keys)
844 } label: {
845 if let symbol = key.symbol { Label(key.label, systemImage: symbol) } else { Text(key.label).font(.callout.weight(.semibold)) }
846 }
847 .accessibilityLabel(key.label)
848 }
849 ForEach(Self.emphasis, id: \.command) { item in
850 Button(item.label, systemImage: item.symbol) { editor.run(item.command) }
851 }
852 Button("Hide keyboard", systemImage: "keyboard.chevron.compact.down") { editor.textView.resignFirstResponder() }
853 }
854 .labelStyle(.iconOnly)
855 .buttonStyle(.bordered)
856 .padding(.horizontal, 8)
857 .padding(.vertical, 6)
858 }
859 .background(.bar)
860 }
861}
862
863/// A command's question: text with choices, a date, or fast selection by keys.
864struct PromptSheet: View {
865 let prompt: Prompt
866 let answer: (String?) -> Void
867 @State private var text = ""
868 @State private var date = Date()
869 @State private var withTime = false
870 @State private var keys: [FastSelection.Input] = []
871
872 var body: some View {
873 NavigationStack {
874 Form {
875 if let fast = prompt.fast {
876 fastSection(fast)
877 } else {
878 Section {
879 TextField(prompt.message, text: $text)
880 .autocorrectionDisabled()
881 .textInputAutocapitalization(.never)
882 .onSubmit { answer(text) }
883 } footer: {
884 if prompt.date != nil { Text("Org's date syntax works too: +2d, fri, 14:00") }
885 }
886 if prompt.date != nil {
887 DatePicker("Date", selection: $date, displayedComponents: [.date])
888 .datePickerStyle(.graphical)
889 .onChange(of: date) { text = QuestionField.stamp(date, withTime: withTime) }
890 Toggle("Time", isOn: $withTime)
891 .onChange(of: withTime) {
892 if withTime { date = QuestionField.timed(date) }
893 text = QuestionField.stamp(date, withTime: withTime)
894 }
895 if withTime { DatePicker("Time", selection: $date, displayedComponents: .hourAndMinute) }
896 }
897 if !prompt.choices.isEmpty {
898 let matching = prompt.choices.filter { lastPart.isEmpty || $0.localizedCaseInsensitiveContains(lastPart) }
899 Section("Choices") {
900 ForEach(matching.prefix(50), id: \.self) { choice in
901 Button(choice) { choose(choice) }
902 }
903 }
904 }
905 }
906 }
907 .navigationTitle(prompt.message.trimmingCharacters(in: CharacterSet(charactersIn: ": ")))
908 .navigationBarTitleDisplayMode(.inline)
909 .toolbar {
910 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { answer(nil) } }
911 if prompt.fast == nil || prompt.fast?.multiple == true {
912 ToolbarItem(placement: .confirmationAction) {
913 Button("Done") { answer(prompt.fast == nil ? text : FastSelection.encode(keys)) }
914 .disabled(prompt.requireMatch && prompt.fast == nil && !prompt.choices.isEmpty && !prompt.choices.contains(text))
915 }
916 }
917 }
918 }
919 .onAppear {
920 text = prompt.initial
921 date = prompt.date?.defaultDate ?? Calendar.current.startOfDay(for: Date())
922 }
923 }
924
925 /// With a separator (tags), what's typed after the last one.
926 private var lastPart: String {
927 guard let separator = prompt.completionSeparator else { return text }
928 return String(text.split(separator: separator, omittingEmptySubsequences: false).last ?? "")
929 }
930
931 private func choose(_ choice: String) {
932 guard let separator = prompt.completionSeparator else {
933 text = choice
934 if prompt.date == nil { answer(choice) }
935 return
936 }
937 var parts = text.split(separator: separator, omittingEmptySubsequences: false).map(String.init)
938 if parts.isEmpty { parts = [""] }
939 parts[parts.count - 1] = choice
940 text = parts.joined(separator: String(separator)) + String(separator)
941 }
942
943 @ViewBuilder
944 private func fastSection(_ fast: FastSelection) -> some View {
945 let current = fast.multiple ? fast.tags(after: keys) ?? [] : []
946 Section {
947 ForEach(Array(fast.options.enumerated()), id: \.offset) { _, option in
948 Button {
949 if fast.multiple { keys.append(.key(option.key)) } else { answer(String(option.key)) }
950 } label: {
951 HStack {
952 Text(option.name).foregroundStyle(.primary)
953 Spacer()
954 if current.contains(option.name) { Image(systemName: "checkmark") }
955 Text(String(option.key)).font(.caption.monospaced()).foregroundStyle(.secondary)
956 }
957 }
958 }
959 if !fast.multiple {
960 Button("No keyword") { answer(" ") }
961 }
962 } footer: {
963 if fast.multiple, !fast.inherited.isEmpty { Text("Inherited: :" + fast.inherited.joined(separator: ":") + ":") }
964 }
965 }
966}
967
968/// `org-edit-special` and `org-table-edit-field`: the text edited apart, put back with Save.
969/// A src block's code is highlighted as its language.
970struct BlockEditSheet: View {
971 let edit: BlockEdit
972 let theme: MobileTheme
973 let finish: (String?) -> Void
974 @State private var text: String?
975
976 var body: some View {
977 NavigationStack {
978 Group {
979 if let text {
980 CodeTextView(text: text, language: edit.language, theme: theme) { self.text = $0 }
981 }
982 }
983 .padding(.horizontal, 8)
984 .navigationTitle(edit.title.replacingOccurrences(of: "Editing ", with: "").capitalized(with: nil))
985 .navigationBarTitleDisplayMode(.inline)
986 .toolbar {
987 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { finish(nil) } }
988 ToolbarItem(placement: .confirmationAction) { Button("Save") { finish(text ?? edit.content) } }
989 }
990 }
991 .onAppear { text = edit.content }
992 }
993}
994
995/// A text view for code, restyled with the editor's highlighter after each change.
996struct CodeTextView: UIViewRepresentable {
997 let text: String
998 let language: String?
999 let theme: MobileTheme
1000 let changed: (String) -> Void
1001
1002 func makeUIView(context: Context) -> UITextView {
1003 let view = UITextView()
1004 view.autocorrectionType = .no
1005 view.autocapitalizationType = .none
1006 view.smartQuotesType = .no
1007 view.smartDashesType = .no
1008 view.spellCheckingType = .no
1009 view.keyboardDismissMode = .interactive
1010 view.backgroundColor = .clear
1011 view.text = text
1012 view.delegate = context.coordinator
1013 context.coordinator.style(view)
1014 DispatchQueue.main.async { view.becomeFirstResponder() }
1015 return view
1016 }
1017
1018 func updateUIView(_ view: UITextView, context: Context) {
1019 context.coordinator.parent = self
1020 }
1021
1022 func makeCoordinator() -> Coordinator { Coordinator(self) }
1023
1024 @MainActor
1025 final class Coordinator: NSObject, UITextViewDelegate {
1026 var parent: CodeTextView
1027 init(_ parent: CodeTextView) { self.parent = parent }
1028
1029 func textViewDidChange(_ view: UITextView) {
1030 parent.changed(view.text)
1031 style(view)
1032 }
1033
1034 /// The theme's font and color, then the language's token colors.
1035 func style(_ view: UITextView) {
1036 let storage = view.textStorage
1037 let whole = NSRange(location: 0, length: storage.length)
1038 let base: [NSAttributedString.Key: Any] = [.font: parent.theme.font, .foregroundColor: parent.theme.foreground]
1039 storage.beginEditing()
1040 storage.setAttributes(base, range: whole)
1041 if let language = parent.language {
1042 for run in MobileEditor.highlighter.highlights(language: language, code: storage.string) {
1043 guard let key = run.category.themeKey, let color = parent.theme.color(key), run.range.upperBound <= storage.length else { continue }
1044 storage.addAttribute(.foregroundColor, value: color, range: NSRange(location: run.range.lowerBound, length: run.range.count))
1045 }
1046 }
1047 storage.endEditing()
1048 view.typingAttributes = base
1049 }
1050 }
1051}
1052
1053/// Every command that applies at the caret, by name.
1054struct CommandPalette: View {
1055 let editor: MobileEditor
1056 /// The pane commands are offered (on iPad), and those for more than one pane.
1057 var panes = false
1058 var split = false
1059 /// Called with the chosen command before the palette closes.
1060 let choose: (String) -> Void
1061 @State private var query = ""
1062 @Environment(\.dismiss) private var dismiss
1063
1064 private static let viewCommands: [(id: String, title: String)] = [
1065 ("org.cycle", "Cycle Visibility"), ("org.cycle-global", "Cycle Global Visibility"),
1066 ("edit.undo", "Undo"), ("edit.redo", "Redo"),
1067 ("app.clock.in", "Clock In"), ("app.clock.out", "Clock Out"), ("app.clock.cancel", "Cancel Clock"),
1068 ("app.clock.goto", "Go to Clocked Entry"), ("app.clock.in-recent", "Clock In to Recent Entry…"),
1069 ("app.clock.in-last", "Clock In to Last Entry"), ("app.clock.goto-recent", "Go to Recent Clocked Entry…"),
1070 ("app.clock.default", "Mark as Default Clock Task"), ("app.clock.resolve", "Resolve Open Clocks…"),
1071 ("app.refile", "Refile…"), ("app.refile.copy", "Copy to Refile Target…"), ("app.refile.goto", "Go to Refile Target…"),
1072 ("app.archive", "Archive Subtree"), ("app.copy-rich-text", "Copy as Rich Text"), ("app.export.html-open", "Export to HTML and Open"),
1073 ("app.export.icalendar-agenda", "Export Agenda Files to iCalendar"), ("app.export.icalendar-combined", "Combine Agenda Files into iCalendar"),
1074 ("app.publish", "Publish Project…"), ("app.publish.all", "Publish All Projects"), ("app.publish.current-file", "Publish Current File"),
1075 ("app.publish.current-project", "Publish Current Project"),
1076 ("app.toggle-markup", "Show or Hide Markup"),
1077 ("org.toggle-inline-images", "Show or Hide Inline Images"), ("org.latex-preview", "Show or Hide LaTeX Previews"), ("editor.toggle-truncate-lines", "Truncate or Wrap Long Lines"), ("editor.toggle-auto-fill", "Turn Auto Fill On or Off"),
1078 ("edit.isearch-forward", "Incremental Search"), ("edit.isearch-backward", "Incremental Search Backward"),
1079 ("org.table.toggle-column-width", "Shrink or Expand Table Column"), ("org.table.shrink", "Shrink Table Columns with Widths"),
1080 ("org.table.expand", "Expand Table Columns"),
1081 ("app.table-import", "Import Table from File…"), ("app.table-export", "Export Table to File…"), ("app.plot", "Plot Table"),
1082 ("app.crypt.encrypt-entry", "Encrypt Entry…"), ("app.crypt.open-entry", "Decrypt Entry…"), ("app.crypt.decrypt-entry", "Decrypt Entry in File…"),
1083 ("app.crypt.encrypt-entries", "Encrypt Tagged Entries…"), ("app.crypt.forget-passphrase", "Forget Encryption Passphrase"),
1084 ("app.backlinks", "Show Backlinks"), ("app.node.find", "Find Node…"), ("app.node.insert", "Insert Node Link…"),
1085 ("app.node.rename-from-front-matter", "Rename Note from Front Matter"),
1086 ("app.node.rename", "Rename Note…"),
1087 ("app.node.rename-folder-from-front-matter", "Rename Notes in Folder from Front Matter…"),
1088 ("app.node.silo-find", "Find Note in Silo…"),
1089 ("app.node.silo-create", "New Note in Silo…"),
1090 ("app.node.sequence-new-parent", "New Sequence Note…"),
1091 ("app.node.sequence-new-child", "New Child Sequence Note…"),
1092 ("app.node.sequence-new-sibling", "New Sibling Sequence Note…"),
1093 ("app.node.sequence-new-child-of-current", "New Child of This Note…"),
1094 ("app.node.sequence-new-sibling-of-current", "New Sibling of This Note…"),
1095 ("app.node.sequence-find", "Find Sequence Relatives…"),
1096 ("app.node.sequence-next-sibling", "Next Sibling Note"),
1097 ("app.node.sequence-previous-sibling", "Previous Sibling Note"),
1098 ("app.node.sequence-reparent", "Reparent Note…"),
1099 ("app.node.sequence-reparent-recursive", "Reparent Note with Descendants…"),
1100 ("app.node.sequence-rename-as-parent", "Rename Note as Sequence Parent"),
1101 ("app.node.sequence-convert", "Convert Note Sequence Scheme"),
1102 ("app.node.sequence-link", "Insert Sequence Link…"),
1103 ("app.node.sequence-hierarchy", "Sequence Hierarchy…"),
1104 ("app.dailies.today", "Go to Today's Daily Note"), ("app.dailies.yesterday", "Go to Yesterday's Daily Note"),
1105 ("app.dailies.tomorrow", "Go to Tomorrow's Daily Note"), ("app.dailies.date", "Go to Daily Note for Date…"),
1106 ("app.dailies.capture-today", "Capture to Today's Daily Note"), ("app.dailies.capture-yesterday", "Capture to Yesterday's Daily Note"),
1107 ("app.dailies.capture-tomorrow", "Capture to Tomorrow's Daily Note"), ("app.dailies.capture-date", "Capture to Daily Note for Date…"),
1108 ("app.dailies.next", "Next Daily Note"), ("app.dailies.previous", "Previous Daily Note"),
1109 ("app.attach.attach", "Attach File…"), ("app.attach.url", "Attach File from URL…"), ("app.attach.new", "New Attachment…"),
1110 ("app.attach.open", "Open Attachment…"), ("app.attach.reveal", "Show Attachment Folder"), ("app.attach.delete", "Delete Attachment…"),
1111 ("app.attach.delete-all", "Delete All Attachments…"), ("app.attach.sync", "Sync Attachments"),
1112 ("app.attach.set-directory", "Set Attachment Folder…"), ("app.attach.unset-directory", "Unset Attachment Folder"),
1113 ]
1114
1115 /// The commands that apply at the caret and their keys, worked out once when the palette
1116 /// opens rather than on every keystroke in the search field.
1117 @State private var applicable: [(id: String, title: String, keys: String?)]?
1118
1119 var body: some View {
1120 let shown = (applicable ?? []).filter { query.isEmpty || $0.title.localizedCaseInsensitiveContains(query) }
1121 NavigationStack {
1122 List(shown, id: \.id) { command in
1123 Button {
1124 choose(command.id)
1125 dismiss()
1126 } label: {
1127 HStack {
1128 Text(command.title).foregroundStyle(.primary)
1129 Spacer()
1130 if let keys = command.keys {
1131 Text(keys).font(.caption.monospaced()).foregroundStyle(.secondary)
1132 }
1133 }
1134 }
1135 }
1136 .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always))
1137 .navigationTitle("Commands")
1138 .navigationBarTitleDisplayMode(.inline)
1139 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Close") { dismiss() } } }
1140 }
1141 .onAppear {
1142 guard applicable == nil else { return }
1143 let context = editor.editContext()
1144 let paneCommands: [(id: String, title: String)] = !panes ? [] : [("app.split-right", "Split Pane Right"), ("app.split-below", "Split Pane Below")]
1145 + (split ? [("app.pane-next", "Next Pane"), ("app.pane-close", "Close Pane"), ("app.pane-only", "Close Other Panes")] : [])
1146 applicable = paneCommands.map { ($0.id, CommandTitle.localized($0.title), editor.keymap.keyLabels(for: $0.id).first) } + (Self.viewCommands + Commands.everything.map { ($0.id, $0.title) })
1147 .filter { editor.applies($0.id, in: context) }
1148 .map { ($0.id, CommandTitle.localized($0.title), editor.keymap.keyLabels(for: $0.id).first) }
1149 }
1150 }
1151}
1152/// A table as CSV or TSV, for the save dialog.
1153struct TableFile: FileDocument {
1154 static var readableContentTypes: [UTType] { [.commaSeparatedText, .tabSeparatedText] }
1155 let text: String
1156 let type: UTType
1157
1158 init(text: String, type: UTType) {
1159 self.text = text
1160 self.type = type
1161 }
1162
1163 init(configuration: ReadConfiguration) throws {
1164 text = configuration.file.regularFileContents.map { String(decoding: $0, as: UTF8.self) } ?? ""
1165 type = configuration.contentType
1166 }
1167
1168 func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
1169 FileWrapper(regularFileWithContents: Data(text.utf8))
1170 }
1171}
1172/// A plotted table, as the Mac's plot sheet shows it.
1173struct PlotScreen: View {
1174 let plot: TablePlot.Plot
1175 @Environment(\.dismiss) private var dismiss
1176
1177 var body: some View {
1178 NavigationStack {
1179 PlotChart(plot)
1180 .navigationTitle("Plot")
1181 .navigationBarTitleDisplayMode(.inline)
1182 .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } }
1183 }
1184 }
1185}
1186/// A file from the photo picker, copied out of the picker's temporary place with its name.
1187struct PickedFile: Transferable {
1188 let url: URL
1189
1190 static var transferRepresentation: some TransferRepresentation {
1191 FileRepresentation(importedContentType: .item) { received in
1192 let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
1193 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
1194 let url = folder.appendingPathComponent(received.file.lastPathComponent)
1195 try FileManager.default.copyItem(at: received.file, to: url)
1196 return PickedFile(url: url)
1197 }
1198 }
1199}
1200
1201/// The passphrase sheet for org-crypt, its new text applied in the editor.
1202struct CryptScreen: View {
1203 let request: CryptRequest
1204 let session: DocumentSession
1205 let editor: MobileEditor?
1206 let report: (String) -> Void
1207 @Environment(\.dismiss) private var dismiss
1208
1209 var body: some View {
1210 NavigationStack {
1211 CryptSheet(request: request, text: { session.document?.text ?? "" }, apply: apply) { message in
1212 dismiss()
1213 if let message { report(message) }
1214 }
1215 .navigationBarTitleDisplayMode(.inline)
1216 }
1217 }
1218
1219 private func apply(_ new: String) {
1220 guard let editor else { return }
1221 let context = editor.editContext()
1222 let caret = min(context.caret, (new as NSString).length)
1223 _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
1224 }
1225}
1226/// The pane an editor screen made for itself, closed with the screen.
1227@MainActor
1228final class PaneHolder {
1229 var pane: EditorPane?
1230 nonisolated(unsafe) var release: (() -> Void)?
1231
1232 deinit {
1233 guard let release else { return }
1234 Task { @MainActor in release() }
1235 }
1236}
1237
1238/// The screen's title, unless a split shows the focused pane's.
1239private struct EditorTitle: ViewModifier {
1240 let title: String
1241 let shown: Bool
1242
1243 func body(content: Content) -> some View {
1244 if shown {
1245 content.navigationTitle(title).navigationBarTitleDisplayMode(.inline)
1246 } else {
1247 content
1248 }
1249 }
1250}
1251#endif