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