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