Sources/OrgstarMobile/EditorScreen.swift
1421 lines · 73436 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 /// Runs a user command once its file is trusted on this device.
424 private func runUserCommand(_ request: UserCommandRequest) {
425 guard let modules = session.userCommands.folder else { return }
426 if let refusal = session.refusesUserCommand(path) { return message = refusal }
427 let ask: @MainActor (Prompt, @escaping (String?) -> Void) -> Void = { prompt = PromptRequest(prompt: $0, reply: $1) }
428 UserCommandTrust.check(request.command, modules: modules, trust: trust, ask: ask, run: {
429 guard let context = editor?.editContext() else { return }
430 message = String(localized: "Running \(request.command.title)…", comment: "A user command started on iPhone and iPad")
431 session.startUserCommand(request, context: context, file: UserCommandFile.relativePath(path, roots: workspace.rootPaths), ask: ask) { message = $0 }
432 }, refuse: { message = $0 })
433 }
434
435 private func start() {
436 let pane: EditorPane
437 if let existing = self.pane {
438 pane = existing
439 } else {
440 pane = session.makePane()
441 holder.pane = pane
442 let store = model.editors, path = path
443 holder.release = { [weak session] in
444 store.release(pane.id, path: path)
445 session?.closePane(pane)
446 }
447 }
448 if pane.path != path { session.open(path, in: pane) }
449 if session.unlockRequest == path {
450 sheet = .crypt(CryptRequest(mode: .openFile, path: path, offset: 0))
451 return
452 }
453 model.editors.prune(session)
454 guard let editor = model.editors.editor(for: path, session: session, make: makeEditor) else { return }
455 let view = model.editors.view(for: pane.id, of: editor)
456 editor.onFocus[ObjectIdentifier(view)] = { [weak session] in
457 session?.focused = pane
458 bind(editor)
459 onFocus()
460 }
461 // A pane a split adds leaves focus where it was, as `split-window` does.
462 if isFocused {
463 session.focused = pane
464 bind(editor)
465 editor.focus(view)
466 model.handoffPath = path
467 }
468 // A kept editor missed settings changed while it was off screen.
469 editor.options = editorOptions
470 self.editor = editor
471 textView = view
472 if let offset { editor.reveal(offset) }
473 if let template = SnippetLibrary.shared.takeTemplate(for: path) { DispatchQueue.main.async { _ = editor.perform(ExpandNamedSnippet(snippet: template)) } }
474 countVersions()
475 if pane.conflict != nil {
476 sheet = .conflict
477 } else if syncCopies > 0 {
478 message = String(localized: "\(syncCopies) sync conflict copies of this file; Resolve Sync Conflicts… in the toolbar compares them.")
479 }
480 }
481
482 /// Counts the focused file's sync conflict copies and recovery versions.
483 private func countVersions() {
484 guard isFocused else { return }
485 syncCopies = session.syncConflictCopies().count
486 recoveries = session.recoveryVersions().count
487 }
488
489 private func makeEditor() -> MobileEditor? {
490 guard let document = session.document(of: path) else { return nil }
491 let editor = MobileEditor(
492 document: document, editable: document.isEditable, options: editorOptions, theme: model.theme,
493 showMarkup: model.showMarkup, baseDirectory: URL(fileURLWithPath: path).deletingLastPathComponent(),
494 mode: DocumentSession.isOrgPath(path) ? .org : Markdown.isPath(path) ? .markdown : .plain
495 )
496 let path = path
497 editor.fileName = path
498 editor.attachmentPath = { DocumentSession.attachmentPath($0, at: $1, tree: $2, path: path) }
499 return editor
500 }
501
502 /// The editor's callbacks go to this screen: it's shown here, or its view here took focus.
503 private func bind(_ editor: MobileEditor) {
504 editor.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] }
505 editor.completionSource = { [index = workspace.index, path] query in await CompletionSources.answer(query, index: index, excluding: path) }
506 editor.createID = { [weak session] item in session.flatMap { CompletionSources.createID(item, session: $0) } }
507 editor.otherBuffers = { [weak session, path] in session.map { CompletionSources.otherBuffers($0, excluding: path) } ?? [] }
508 editor.onChange = { [weak session] in session?.bufferChanged(path) }
509 editor.onSelect = { [weak model] in model?.handoff.changed() }
510 editor.onMessage = { message = $0 }
511 editor.onPrompt = { prompt, reply in self.prompt = PromptRequest(prompt: prompt, reply: reply) }
512 editor.onLink = { link in follow(link) }
513 editor.onEditBlock = { edit in sheet = .block(edit) }
514 editor.onColumnView = { view in sheet = .columns(view) }
515 editor.onTangle = { scope in if ProAccess.shared.allows(.babel) { message = session.tangle(scope) } }
516 editor.onBabel = { job in if ProAccess.shared.allows(.babel) { run(job) } }
517 editor.onUserCommand = { request in runUserCommand(request) }
518 editor.onRefreshSetup = { session.refreshSetup() }
519 editor.onAgenda = { start, count in model.agendaRequest = .init(start: start, count: count) }
520 editor.keymap = model.keymap
521 editor.modal = model.modalKeys
522 // Dropped files are copies the drop made, so they are attached, not linked or opened.
523 editor.onFiles = { attachActions.drop($0, method: .attach, attachMethod: .mv) }
524 editor.onImage = { attachActions.yankImage($0, ext: $1) }
525 editor.onAppCommand = { id in
526 if let feature = ProFeature.required(byCommand: id), !ProAccess.shared.allows(feature) { return }
527 if Self.paneCommands.contains(id) {
528 if let onPaneCommand { if let text = onPaneCommand(id) { message = text } } else { message = MobileEditor.unavailable(command: id) }
529 } else if id == "app.save" {
530 _ = session.save(path)
531 } else if id == "app.babel.cancel" {
532 if session.isRunningUserCommand {
533 session.cancelUserCommand()
534 } else if session.isRunningBabel {
535 session.cancelBabel()
536 } else {
537 message = String(localized: "Nothing is running")
538 }
539 } else if id == "app.archive" {
540 if let caret = self.editor?.editContext().caret { message = session.archive(from: (path, caret)) }
541 } else if id == "app.copy-rich-text" {
542 if let text = session.document(of: path)?.text { message = ExportItems.copy(path: path, text: text, theme: model.theme) }
543 } else if id == "app.export-dialog" {
544 sheet = .export
545 } else if id == EditorScreen.exportSubtreeCommand {
546 exportSubtree()
547 } else if Printing.commands.contains(id) {
548 printFile(id)
549 } else if id == "app.present" {
550 if let document = session.document(of: path),
551 let deck = SlideDeck(tree: document.tree, path: path, settings: document.defaults, caret: self.editor?.editContext().caret ?? 0) {
552 self.deck = deck
553 } else {
554 message = String(localized: "Nothing to present")
555 }
556 } else if id == "app.share-subtree" {
557 if let caret = self.editor?.editContext().caret, let refusal = session.refusesSubtreeShare(path, at: caret) {
558 message = refusal
559 } else if let caret = self.editor?.editContext().caret, let share = session.subtreeShare(path, at: caret) {
560 sheet = .shareSubtree(share)
561 } else {
562 message = String(localized: "Not in a subtree")
563 }
564 } else if id == "app.export.html-open" {
565 exportHTMLAndOpen()
566 } else if id == "app.export-body-only" {
567 let on = !ExportSettings.saved(for: path).bodyOnly
568 ExportItems.setBodyOnly(on, path: path)
569 message = on ? "Export: body only" : "Export: whole document"
570 } else if id == "app.export.icalendar-agenda" || id == "app.export.icalendar-combined" {
571 agendaCalendars(combined: id == "app.export.icalendar-combined")
572 } else if id.hasPrefix("app.publish") {
573 publish(id)
574 } else if AppStoreCommands.unavailable(id) {
575 message = "Attachments can't be linked on iPhone and iPad; Attach File… copies the file."
576 } else if ["app.refile", "app.refile.copy", "app.refile.goto"].contains(id) {
577 sheet = .refile(id)
578 } else if id == "app.table-import" {
579 importingTable = true
580 } else if id == "app.table-export" || id == "app.table-export.tsv" {
581 exportTable(csv: id == "app.table-export")
582 } else if id == "app.word-count" {
583 message = wordCount()
584 } else if id == "app.recovery" {
585 sheet = .recovery
586 } else if id == "app.sync-conflicts" {
587 sheet = .syncCopies
588 } else if id == "app.attach.photo" {
589 attachingPhotos = true
590 } else if id == "app.attach.camera" {
591 takingPhoto = true
592 } else if id == "app.attach.scan" {
593 scanning = true
594 } else if id == "app.plot" {
595 plotTable()
596 } else if id.hasPrefix("app.crypt.") {
597 crypt(id)
598 } else if id.hasPrefix("app.attach.") {
599 attachActions.run(id)
600 } else if id == "app.node.graph" {
601 sheet = .graph
602 } else if id.hasPrefix("app.dailies.") || id.hasPrefix("app.node.") {
603 roamActions.run(id)
604 } else if id == "app.backlinks" {
605 sheet = .backlinks
606 } else if let kind = ReplaceKind(command: id), kind != .replace {
607 let context = self.editor?.editContext()
608 sheet = .rename(kind, context.map { kind.initial(text: $0.text, caret: $0.caret, keywords: $0.tree.settings.todoKeywordNames) } ?? "")
609 } else if id == "app.lint-folders" {
610 sheet = .lintFolders
611 } else if id == "app.flashcards.review" {
612 model.reviewRequested = true
613 } else if id == "app.lint" {
614 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") }
615 } else if id == "app.working-copy.sync" {
616 if let root = model.workingCopy.root(containing: path, roots: workspace.rootPaths) {
617 model.workingCopy.sync(root, session: session)
618 } else {
619 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")
620 }
621 } else if id == "app.toggle-markup" {
622 model.showMarkup.toggle()
623 } else if id == "app.cite.insert" {
624 citationActions.insert()
625 } else if MobileEditor.linkCommands.contains(id) {
626 link(id)
627 } else if !MobileClock.run(id, model: model, workspace: workspace, show: { message = $0 }) {
628 message = MobileEditor.unavailable(command: id)
629 }
630 }
631 }
632}
633
634extension EditorScreen {
635 /// Follows a link; Markdown and text files open in the editor, other files it doesn't open
636 /// show in Quick Look.
637 private func follow(_ link: OrgLink) {
638 switch session.follow(link, workspace: workspace, isText: { Markdown.isPath($0) || Markdown.isPlainTextPath($0) }) {
639 case .shown:
640 // A link to another file shows it on its own screen; this pane keeps its file.
641 guard let pane, let target = pane.path, target != path else { message = nil; return }
642 let caret = session.caret(of: target) ?? 0
643 session.open(path, in: pane)
644 model.openRequest = .offset(target, caret)
645 case .openExternally(let url): if url.isFileURL { previewed = url } else { openURL(url) }
646 case .message(let text): message = text
647 case .choose(let question, let paths):
648 let labels = paths.map { ($0 as NSString).lastPathComponent }
649 prompt = PromptRequest(prompt: Prompt(key: "file", message: question, choices: labels)) { answer in
650 guard let answer, let index = labels.firstIndex(of: answer) else { return }
651 follow(OrgLink(type: "file", path: paths[index], raw: "file:" + paths[index]))
652 }
653 case .citation(let keys):
654 citationActions.follow(keys)
655 case .elisp(let form):
656 // Once trusted, as `org-link-elisp-confirm-function` asks.
657 let go = { _ = Task { message = await session.evaluateLink(form) } }
658 let content = "elisp:" + form
659 if trust.isTrusted(path: path, content: content) { return go() }
660 prompt = PromptRequest(prompt: Prompt(key: "confirm", message: "Execute \(form) as Elisp?", choices: ["yes", "no", "always"])) { answer in
661 switch answer {
662 case "always":
663 trust.trust(path: path, content: content)
664 go()
665 case "yes": go()
666 default: message = "Not run"
667 }
668 }
669 }
670 }
671
672 /// org-roam's daily notes and nodes.
673 private var roamActions: RoamActions {
674 var actions = RoamActions(
675 session: session, roots: { workspace.rootPaths },
676 nodes: { try workspace.nodes(overlay: workspace.overlay(session.openDocuments)) },
677 show: { message = $0 }, ask: { prompt = PromptRequest(prompt: $0, reply: $1) },
678 open: { file, offset in
679 if file == path { editor?.reveal(offset) } else { model.openRequest = .offset(file, offset) }
680 },
681 insertLink: { link, title in
682 guard let editor else { return }
683 let context = editor.editContext()
684 let range = context.selection.first ?? context.caret..<context.caret
685 let selected = (context.text as NSString).substring(with: NSRange(range))
686 let text = Denote.linkText(link, description: selected.isEmpty ? title : selected, inFile: context.options.filePath)
687 let end = range.lowerBound + (text as NSString).length
688 _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: [TextEdit(range: range, replacement: text)], selection: [end..<end])))
689 },
690 refresh: { Task { await workspace.refresh() } })
691 actions.capture = { model.captureRequest = CaptureRequest(roam: $0) }
692 return actions
693 }
694
695 /// Insert Citation… and following citations.
696 private var citationActions: CitationActions {
697 CitationActions(
698 session: session, context: { editor?.editContext() }, perform: { _ = editor?.perform($0) },
699 show: { message = $0 }, ask: { prompt = PromptRequest(prompt: $0, reply: $1) }, present: { citationEntry = $0 })
700 }
701
702 /// org-attach's commands for the entry at the caret.
703 private var attachActions: AttachActions {
704 AttachActions(
705 entry: {
706 guard let editor else { return nil }
707 let context = editor.editContext()
708 return Attachments.Entry(text: context.text, offset: context.caret, path: path, options: context.options)
709 },
710 apply: { new, caret in
711 guard let editor else { return }
712 let context = editor.editContext()
713 let caret = min(caret ?? context.caret, (new as NSString).length)
714 _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
715 },
716 show: { message = $0 },
717 ask: { prompt = PromptRequest(prompt: $0, reply: $1) },
718 storeLink: { _ = StoredLink.add($0, to: &model.storedLinks) },
719 open: { follow(OrgLink(type: "file", path: $0, raw: "file:" + $0)) },
720 reveal: { dir in
721 if let url = URL(string: "shareddocuments://" + (dir.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? dir)) { openURL(url) }
722 },
723 pick: { attaching = $0 })
724 }
725
726 /// Photos and videos attached under the names Photos gives them, linked at the caret.
727 private func attachPhotos(_ items: [PhotosPickerItem]) {
728 Task { @MainActor in
729 var urls: [URL] = []
730 for item in items {
731 if let picked = try? await item.loadTransferable(type: PickedFile.self) { urls.append(picked.url) }
732 }
733 if urls.count < items.count { message = "Can't read \(items.count - urls.count) of the items" }
734 if !urls.isEmpty { attachActions.drop(urls, method: .attach, attachMethod: .mv) }
735 }
736 }
737
738 /// `org-table-import`: a TSV, CSV or space-separated file becomes a table at the caret.
739 private func importTable(_ result: Result<URL, Error>) {
740 guard case .success(let url) = result, let editor else { return }
741 let scoped = url.startAccessingSecurityScopedResource()
742 defer { if scoped { url.stopAccessingSecurityScopedResource() } }
743 guard let contents = try? String(contentsOf: url, encoding: .utf8) else { return message = "Can't read \(url.lastPathComponent)" }
744 _ = editor.perform(ImportTable(contents: contents))
745 }
746
747 /// The export formats for the subtree at the caret, as the Mac's export sheet's scope.
748 private func exportSubtree() {
749 guard let context = editor?.editContext() else { return }
750 guard ExportScope.subtree(context.text, at: context.caret) != nil else { return message = "Not in a subtree" }
751 sheet = .exportSubtree(context.caret)
752 }
753
754 /// Print…, Print Subtree… and Print Selection…, from Commands.
755 private func printFile(_ id: String) {
756 guard let context = editor?.editContext() else { return }
757 let scope: PrintScope
758 switch id {
759 case "app.print-subtree": scope = .subtree(context.caret)
760 case "app.print-selection":
761 guard let selection = context.selection.first(where: { !$0.isEmpty }) else { return message = String(localized: "No text is selected") }
762 scope = .selection(selection)
763 default: scope = .file
764 }
765 ExportItems.startPrinting(path: path, text: context.text, scope: scope, theme: model.theme) { message = $0 }
766 }
767
768 /// `org-html-export-to-html` and open: the page in Quick Look, from a temporary file.
769 private func exportHTMLAndOpen() {
770 guard let text = session.document(of: path)?.text else { return }
771 let html = OrgExport.html(text, path: path, theme: model.theme, bodyOnly: ExportSettings.saved(for: path).bodyOnly)
772 let name = ExportScope.output(for: URL(fileURLWithPath: path), name: ExportScope.fileName(text, settings: OrgPreferences.orgSettings()), extension: "html")
773 .lastPathComponent
774 do {
775 previewed = try HTMLPreview.write(html, directory: URL(fileURLWithPath: path).deletingLastPathComponent(), name: name)
776 } catch {
777 message = "Can't export \(name): \(error.localizedDescription)"
778 }
779 }
780
781 /// The agenda files' calendars written beside them, or combined in one shown in Quick Look,
782 /// whose share button saves or sends it.
783 private func agendaCalendars(combined: Bool) {
784 guard let calendars = AgendaCalendars(model: model) else { return message = "No agenda files" }
785 guard combined else { return message = calendars.exportEach() }
786 do {
787 previewed = try calendars.combined()
788 } catch {
789 message = "Can't export: \(error.localizedDescription)"
790 }
791 }
792
793 /// `org-publish` and its variants, for the `[[publish]]` projects in config.toml.
794 private func publish(_ id: String) {
795 guard let all = publishProjects() else { return }
796 let current = Publish.projects(containing: path, in: all)
797 switch id {
798 case "app.publish.all":
799 publish(all.map(\.name))
800 case "app.publish.current-file":
801 guard let project = current.first else { return message = "File is not part of any known project" }
802 publish([project.name], only: path)
803 case "app.publish.current-project":
804 guard let project = current.first else { return message = "File is not part of any known project" }
805 publish([project.name])
806 default:
807 prompt = PromptRequest(prompt: Prompt(key: "project", message: "Publish project:", choices: all.map(\.name))) { answer in
808 if let answer, all.contains(where: { $0.name == answer }) { publish([answer]) }
809 }
810 }
811 }
812
813 /// The projects in config.toml, each publishing to the folder chosen for it; nil, with a
814 /// message, when there are none.
815 private func publishProjects() -> [PublishProject]? {
816 let config = (try? String(contentsOf: UserConfig.file("config.toml"), encoding: .utf8)) ?? ""
817 let loaded = Publish.projects(fromConfig: config, root: workspace.rootPaths.first)
818 if let problem = loaded.problems.first { message = problem }
819 guard !loaded.projects.isEmpty else {
820 message = "No [[publish]] projects in config.toml"
821 return nil
822 }
823 return PublishFolders.shared.applied(to: loaded.projects)
824 }
825
826 /// Publishes the projects named, `only` that file when given. A project that publishes
827 /// outside the folders added to orgstar asks for its folder first, once.
828 private func publish(_ names: [String], only: String? = nil) {
829 guard let all = publishProjects() else { return }
830 let chosen = all.filter { names.contains($0.name) }
831 do {
832 if let project = try PublishFolders.shared.needed(chosen, all: all, roots: workspace.rootPaths).first {
833 message = "Choose the folder \(project.name) publishes to"
834 publishFolder = PublishFolderRequest(project: project.name) { publish(names, only: only) }
835 choosingPublishFolder = true
836 return
837 }
838 if let project = try Publish.expand(chosen, all: all).first(where: { !FileManager.default.fileExists(atPath: $0.baseDirectory) }) {
839 return message = "Can't read \(project.name)'s base-directory, \(OrgPaths.abbreviatingWithTilde(project.baseDirectory))"
840 }
841 let read = { (file: String) -> String? in
842 session.exportText(of: file)
843 }
844 let codeStyle = HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme)
845 // As the Export menu: no author unless the file has #+AUTHOR:.
846 let report = try Publish.publish(chosen, all: all, only: only, author: "", read: read) { function, text, file, bodyOnly in
847 try Publish.export(function, text: text, path: file, bodyOnly: bodyOnly, settings: OrgPreferences.orgSettings(), codeStyle: codeStyle, author: "")
848 }
849 let note = session.openPaths.contains(where: session.exportLeavesOut) ? " " + DocumentSession.exportNote : ""
850 message = (report.skipped.isEmpty ? String(localized: "Published \(report.published.count) files")
851 : String(localized: "Published \(report.published.count) files, \(report.skipped.count) up to date")) + note
852 } catch {
853 message = "\(error)"
854 }
855 }
856
857 /// org-crypt's commands at the caret, through the passphrase sheet.
858 private func crypt(_ id: String) {
859 if let feature = ProFeature.required(byCommand: id), !ProAccess.shared.allows(feature) { return }
860 guard let editor else { return }
861 let context = editor.editContext()
862 switch id {
863 case "app.crypt.forget-passphrase":
864 session.forgetPassphrase(for: path)
865 message = "Passphrase forgotten for \((path as NSString).lastPathComponent)"
866 case "app.crypt.encrypt-entries":
867 sheet = .crypt(CryptRequest(mode: .encryptAll(tag: OrgPreferences.cryptTag()), path: path, offset: context.caret))
868 default:
869 guard OrgCrypt.heading(context.text, at: context.caret) != nil else { return message = "Before first headline" }
870 let encrypted = OrgCrypt.encryptedRange(context.text, at: context.caret) != nil
871 if id == "app.crypt.encrypt-entry" {
872 guard !encrypted else { return message = "The entry is encrypted already" }
873 sheet = .crypt(CryptRequest(mode: .encrypt, path: path, offset: context.caret))
874 } else {
875 guard encrypted else { return message = "Not an encrypted entry" }
876 sheet = .crypt(CryptRequest(mode: id == "app.crypt.open-entry" ? .open : .decryptInPlace, path: path, offset: context.caret))
877 }
878 }
879 }
880
881 /// `org-plot/gnuplot`, drawn by Swift Charts: written to `file:` when the options name
882 /// one, else shown.
883 private func plotTable() {
884 guard let editor else { return }
885 let context = editor.editContext()
886 do {
887 let plot = try TablePlot.plot(context.text, at: context.caret)
888 if let url = PlotOutput.file(plot, directory: URL(fileURLWithPath: path).deletingLastPathComponent()) {
889 try PlotOutput.write(plot, to: url)
890 message = "Plot written to \(url.lastPathComponent)" + (PlotOutput.note(plot).map { ". " + $0 } ?? "")
891 if editor.showsImages { editor.restyleAll() }
892 } else {
893 try PlotOutput.check(plot)
894 sheet = .plot(plot)
895 if let note = PlotOutput.note(plot) { message = note }
896 }
897 } catch {
898 message = "\(error)"
899 }
900 }
901
902 /// `org-table-export` of the table at the caret, as CSV or TSV.
903 /// Words, characters and reading time of the selection, or of the file.
904 private func wordCount() -> String {
905 guard let editor else { return "No file is open" }
906 let text = editor.document.text as NSString
907 let selection = editor.textView.selectedRange
908 let selected = selection.length > 0 && NSMaxRange(selection) <= text.length
909 let counts = TextStats.region(selected ? text.substring(with: selection) : text as String)
910 return (selected ? "Selection: " : "") + TextStats.summary(words: counts.words, characters: counts.characters)
911 }
912
913 private func exportTable(csv: Bool) {
914 guard let editor else { return }
915 let context = editor.editContext()
916 guard let text = ImportTable.exportText(context.text, at: context.caret, path: csv ? "table.csv" : "table.tsv") else {
917 return message = "No table at point"
918 }
919 exportedTable = TableFile(text: text, type: csv ? .commaSeparatedText : .tabSeparatedText)
920 }
921
922 /// `org-refile` of the entry at the caret, to a target worked out again from the files
923 /// now, as the agenda's Refile… does.
924 func refile(to target: RefileTarget, keep: Bool = false) {
925 guard let editor, let path = session.path else { return }
926 let caret = editor.editContext().caret
927 guard let current = workspace.refileTargets(openPath: path, document: session.document).first(where: { $0.label == target.label }) else {
928 message = "Can't find \(target.label) any more."
929 return
930 }
931 message = session.refile(to: current, from: (path, caret), keep: keep)
932 }
933}
934
935/// The editor's text view, with the Org key bar over the keyboard.
936struct EditorTextView: UIViewRepresentable {
937 let editor: MobileEditor
938 /// This pane's view of the editor.
939 let view: UITextView
940 let palette: () -> Void
941
942 func makeUIView(context: Context) -> UITextView {
943 let bar = UIHostingController(rootView: KeyBar(editor: editor, palette: palette).dynamicTypeSize(...KeyBar.largestSize))
944 bar.view.frame = CGRect(x: 0, y: 0, width: 400, height: 2 * KeyBar.padding + KeyBar.target)
945 bar.view.backgroundColor = .clear
946 // As tall as its buttons: the input accessory takes the intrinsic height.
947 bar.sizingOptions = .intrinsicContentSize
948 bar.safeAreaRegions = []
949 bar.view.autoresizingMask = .flexibleHeight
950 view.inputAccessoryView = bar.view
951 context.coordinator.bar = bar
952 // The bar's height follows the text size.
953 view.registerForTraitChanges([UITraitPreferredContentSizeCategory.self]) { (view: UITextView, _) in
954 view.inputAccessoryView?.invalidateIntrinsicContentSize()
955 view.reloadInputViews()
956 }
957 return view
958 }
959
960 func updateUIView(_ view: UITextView, context: Context) {}
961
962 func makeCoordinator() -> Coordinator { Coordinator() }
963
964 final class Coordinator {
965 var bar: UIViewController?
966 }
967}
968
969/// A command's question: text with choices, a date, or fast selection by keys.
970struct PromptSheet: View {
971 let prompt: Prompt
972 let answer: (String?) -> Void
973 @State private var text = ""
974 @State private var date = Date()
975 @State private var withTime = false
976 @State private var keys: [FastSelection.Input] = []
977
978 var body: some View {
979 NavigationStack {
980 Form {
981 if let fast = prompt.fast {
982 fastSection(fast)
983 } else {
984 Section {
985 TextField(prompt.message, text: $text)
986 .autocorrectionDisabled()
987 .textInputAutocapitalization(.never)
988 .onSubmit { answer(text) }
989 } footer: {
990 if prompt.date != nil { Text("Org's date syntax works too: +2d, fri, 14:00") }
991 }
992 if prompt.date != nil {
993 DatePicker("Date", selection: $date, displayedComponents: [.date])
994 .datePickerStyle(.graphical)
995 .onChange(of: date) { text = QuestionField.stamp(date, withTime: withTime) }
996 Toggle("Time", isOn: $withTime)
997 .onChange(of: withTime) {
998 if withTime { date = QuestionField.timed(date) }
999 text = QuestionField.stamp(date, withTime: withTime)
1000 }
1001 if withTime { DatePicker("Time", selection: $date, displayedComponents: .hourAndMinute) }
1002 }
1003 if !prompt.choices.isEmpty {
1004 let matching = prompt.choices.filter { lastPart.isEmpty || $0.localizedCaseInsensitiveContains(lastPart) }
1005 Section("Choices") {
1006 ForEach(matching.prefix(50), id: \.self) { choice in
1007 Button(choice) { choose(choice) }
1008 }
1009 }
1010 }
1011 }
1012 }
1013 .navigationTitle(prompt.message.trimmingCharacters(in: CharacterSet(charactersIn: ": ")))
1014 .navigationBarTitleDisplayMode(.inline)
1015 .toolbar {
1016 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { answer(nil) } }
1017 if prompt.fast == nil || prompt.fast?.multiple == true {
1018 ToolbarItem(placement: .confirmationAction) {
1019 Button("Done") { answer(prompt.fast == nil ? text : FastSelection.encode(keys)) }
1020 .disabled(prompt.requireMatch && prompt.fast == nil && !prompt.choices.isEmpty && !prompt.choices.contains(text))
1021 }
1022 }
1023 }
1024 }
1025 .onAppear {
1026 text = prompt.initial
1027 date = prompt.date?.defaultDate ?? Calendar.current.startOfDay(for: Date())
1028 }
1029 }
1030
1031 /// With a separator (tags), what's typed after the last one.
1032 private var lastPart: String {
1033 guard let separator = prompt.completionSeparator else { return text }
1034 return String(text.split(separator: separator, omittingEmptySubsequences: false).last ?? "")
1035 }
1036
1037 private func choose(_ choice: String) {
1038 guard let separator = prompt.completionSeparator else {
1039 text = choice
1040 if prompt.date == nil { answer(choice) }
1041 return
1042 }
1043 var parts = text.split(separator: separator, omittingEmptySubsequences: false).map(String.init)
1044 if parts.isEmpty { parts = [""] }
1045 parts[parts.count - 1] = choice
1046 text = parts.joined(separator: String(separator)) + String(separator)
1047 }
1048
1049 @ViewBuilder
1050 private func fastSection(_ fast: FastSelection) -> some View {
1051 let current = fast.multiple ? fast.tags(after: keys) ?? [] : []
1052 Section {
1053 ForEach(Array(fast.options.enumerated()), id: \.offset) { _, option in
1054 Button {
1055 if fast.multiple { keys.append(.key(option.key)) } else { answer(String(option.key)) }
1056 } label: {
1057 HStack {
1058 Text(option.name).foregroundStyle(.primary)
1059 Spacer()
1060 if current.contains(option.name) { Image(systemName: "checkmark") }
1061 Text(String(option.key)).font(.caption.monospaced()).foregroundStyle(.secondary)
1062 }
1063 }
1064 }
1065 if !fast.multiple {
1066 Button("No Keyword") { answer(" ") }
1067 }
1068 } footer: {
1069 if fast.multiple, !fast.inherited.isEmpty { Text("Inherited: :" + fast.inherited.joined(separator: ":") + ":") }
1070 }
1071 }
1072}
1073
1074/// `org-edit-special` and `org-table-edit-field`: the text edited apart, put back with Save.
1075/// A src block's code is highlighted as its language.
1076struct BlockEditSheet: View {
1077 let edit: BlockEdit
1078 let theme: MobileTheme
1079 let finish: (String?) -> Void
1080 @State private var text: String?
1081
1082 var body: some View {
1083 NavigationStack {
1084 Group {
1085 if let text {
1086 CodeTextView(text: text, language: edit.language, theme: theme) { self.text = $0 }
1087 }
1088 }
1089 .padding(.horizontal, 8)
1090 .navigationTitle(edit.title.replacingOccurrences(of: "Editing ", with: "").capitalized(with: nil))
1091 .navigationBarTitleDisplayMode(.inline)
1092 .toolbar {
1093 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { finish(nil) } }
1094 ToolbarItem(placement: .confirmationAction) { Button("Save") { finish(text ?? edit.content) } }
1095 }
1096 }
1097 .onAppear { text = edit.content }
1098 }
1099}
1100
1101/// A text view for code, restyled with the editor's highlighter after each change.
1102struct CodeTextView: UIViewRepresentable {
1103 let text: String
1104 let language: String?
1105 let theme: MobileTheme
1106 let changed: (String) -> Void
1107
1108 func makeUIView(context: Context) -> UITextView {
1109 let view = UITextView()
1110 view.autocorrectionType = .no
1111 view.autocapitalizationType = .none
1112 view.smartQuotesType = .no
1113 view.smartDashesType = .no
1114 view.spellCheckingType = .no
1115 view.keyboardDismissMode = .interactive
1116 view.backgroundColor = .clear
1117 view.text = text
1118 view.delegate = context.coordinator
1119 context.coordinator.style(view)
1120 DispatchQueue.main.async { view.becomeFirstResponder() }
1121 return view
1122 }
1123
1124 func updateUIView(_ view: UITextView, context: Context) {
1125 context.coordinator.parent = self
1126 }
1127
1128 func makeCoordinator() -> Coordinator { Coordinator(self) }
1129
1130 @MainActor
1131 final class Coordinator: NSObject, UITextViewDelegate {
1132 var parent: CodeTextView
1133 init(_ parent: CodeTextView) { self.parent = parent }
1134
1135 func textViewDidChange(_ view: UITextView) {
1136 parent.changed(view.text)
1137 style(view)
1138 }
1139
1140 /// The theme's font and color, then the language's token colors.
1141 func style(_ view: UITextView) {
1142 let storage = view.textStorage
1143 let whole = NSRange(location: 0, length: storage.length)
1144 let base: [NSAttributedString.Key: Any] = [.font: parent.theme.font, .foregroundColor: parent.theme.foreground]
1145 storage.beginEditing()
1146 storage.setAttributes(base, range: whole)
1147 if let language = parent.language {
1148 for run in MobileEditor.highlighter.highlights(language: language, code: storage.string) {
1149 guard let key = run.category.themeKey, let color = parent.theme.color(key), run.range.upperBound <= storage.length else { continue }
1150 storage.addAttribute(.foregroundColor, value: color, range: NSRange(location: run.range.lowerBound, length: run.range.count))
1151 }
1152 }
1153 storage.endEditing()
1154 view.typingAttributes = base
1155 }
1156 }
1157}
1158
1159/// The editor's commands, those that don't apply at the caret greyed with the reason.
1160struct CommandPalette: View {
1161 let editor: MobileEditor
1162 /// The pane commands are offered (on iPad), and those for more than one pane.
1163 var panes = false
1164 var split = false
1165 /// Recovery versions and sync conflict copies of the file, which their commands show.
1166 var recoveries = 0
1167 var syncCopies = 0
1168 /// Called with the chosen command before the palette closes.
1169 let choose: (String) -> Void
1170
1171 static let viewCommands: [(id: String, title: String)] = [
1172 ("org.cycle", "Cycle Visibility"), ("org.cycle-global", "Cycle Global Visibility"),
1173 ("edit.undo", "Undo"), ("edit.redo", "Redo"),
1174 ("app.clock.in", "Clock In"), ("app.clock.out", "Clock Out"), ("app.clock.cancel", "Cancel Clock"),
1175 ("app.clock.goto", "Go to Clocked Entry"), ("app.clock.in-recent", "Clock In to Recent Entry…"),
1176 ("app.clock.in-last", "Clock In to Last Entry"), ("app.clock.goto-recent", "Go to Recent Clocked Entry…"),
1177 ("app.clock.default", "Mark as Default Clock Task"), ("app.clock.resolve", "Resolve Open Clocks…"),
1178 ("app.refile", "Refile…"), ("app.refile.copy", "Copy to Refile Target…"), ("app.refile.goto", "Go to Refile Target…"),
1179 ("app.archive", "Archive Subtree"), ("app.export-dialog", "Export…"), ("app.export-subtree-dialog", "Export Subtree…"),
1180 ("app.share-subtree", "Share Subtree…"), ("app.print", "Print…"), ("app.print-subtree", "Print Subtree…"), ("app.print-selection", "Print Selection…"),
1181 ("app.present", "Present"),
1182 ("app.copy-rich-text", "Copy as Rich Text"), ("app.export.html-open", "Export to HTML and Open"),
1183 ("app.export-body-only", "Turn Body-Only Export On or Off"),
1184 ("app.export.icalendar-agenda", "Export Agenda Files to iCalendar"), ("app.export.icalendar-combined", "Combine Agenda Files into iCalendar"),
1185 ("app.publish", "Publish Project…"), ("app.publish.all", "Publish All Projects"), ("app.publish.current-file", "Publish Current File"),
1186 ("app.publish.current-project", "Publish Current Project"),
1187 ("app.toggle-markup", "Show or Hide Markup"), ("app.word-count", "Word Count"),
1188 ("org.snippet.next-field", "Next Snippet Field"), ("org.snippet.previous-field", "Previous Snippet Field"),
1189 ("app.recovery", "Recovery Versions…"), ("app.sync-conflicts", "Resolve Sync Conflicts…"), ("app.lint", "Lint File"), ("app.lint-folders", "Lint All Folders"),
1190 ("app.flashcards.review", "Review Flashcards"), ("app.babel.cancel", "Cancel Running Task"),
1191 ("app.working-copy.sync", "Sync with Working Copy"),
1192 ("app.cite.insert", "Insert Citation…"),
1193 ("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"),
1194 ("editor.complete", "Complete at Point"), ("editor.dabbrev-expand", "Expand Word"), ("editor.dabbrev-completion", "Complete Word"),
1195 ("edit.isearch-forward", "Incremental Search"), ("edit.isearch-backward", "Incremental Search Backward"),
1196 ("org.table.toggle-column-width", "Shrink or Expand Table Column"), ("org.table.shrink", "Shrink Table Columns with Widths"),
1197 ("org.table.expand", "Expand Table Columns"),
1198 ("app.table-import", "Import Table from File…"), ("app.table-export", "Export Table to File…"),
1199 ("app.table-export.tsv", "Export Table as TSV…"), ("app.plot", "Plot Table"),
1200 ("app.crypt.encrypt-entry", "Encrypt Entry…"), ("app.crypt.open-entry", "Decrypt Entry…"), ("app.crypt.decrypt-entry", "Decrypt Entry in File…"),
1201 ("app.crypt.encrypt-entries", "Encrypt Tagged Entries…"), ("app.crypt.forget-passphrase", "Forget Encryption Passphrase"),
1202 ("app.rename-tag", "Rename Tag…"), ("app.rename-todo-keyword", "Rename TODO Keyword…"),
1203 ("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"),
1204 ("app.node.rename-from-front-matter", "Rename Note from Front Matter"),
1205 ("app.node.rename", "Rename Note…"),
1206 ("app.node.rename-folder-from-front-matter", "Rename Notes in Folder from Front Matter…"),
1207 ("app.node.silo-find", "Find Note in Silo…"),
1208 ("app.node.silo-create", "New Note in Silo…"),
1209 ("app.node.sequence-new-parent", "New Sequence Note…"),
1210 ("app.node.sequence-new-child", "New Child Sequence Note…"),
1211 ("app.node.sequence-new-sibling", "New Sibling Sequence Note…"),
1212 ("app.node.sequence-new-child-of-current", "New Child of This Note…"),
1213 ("app.node.sequence-new-sibling-of-current", "New Sibling of This Note…"),
1214 ("app.node.sequence-find", "Find Sequence Relatives…"),
1215 ("app.node.sequence-next-sibling", "Next Sibling Note"),
1216 ("app.node.sequence-previous-sibling", "Previous Sibling Note"),
1217 ("app.node.sequence-reparent", "Reparent Note…"),
1218 ("app.node.sequence-reparent-recursive", "Reparent Note with Descendants…"),
1219 ("app.node.sequence-rename-as-parent", "Rename Note as Sequence Parent"),
1220 ("app.node.sequence-convert", "Convert Note Sequence Scheme"),
1221 ("app.node.sequence-link", "Insert Sequence Link…"),
1222 ("app.node.sequence-hierarchy", "Sequence Hierarchy…"),
1223 ("app.dailies.today", "Go to Today's Daily Note"), ("app.dailies.yesterday", "Go to Yesterday's Daily Note"),
1224 ("app.dailies.tomorrow", "Go to Tomorrow's Daily Note"), ("app.dailies.date", "Go to Daily Note for Date…"),
1225 ("app.dailies.capture-today", "Capture to Today's Daily Note"), ("app.dailies.capture-yesterday", "Capture to Yesterday's Daily Note"),
1226 ("app.dailies.capture-tomorrow", "Capture to Tomorrow's Daily Note"), ("app.dailies.capture-date", "Capture to Daily Note for Date…"),
1227 ("app.dailies.next", "Next Daily Note"), ("app.dailies.previous", "Previous Daily Note"),
1228 ("app.attach.attach", "Attach File…"), ("app.attach.photo", "Attach Photo or Video…"), ("app.attach.camera", "Take Photo…"),
1229 ("app.attach.scan", "Scan Document…"), ("app.attach.url", "Attach File from URL…"), ("app.attach.new", "New Attachment…"),
1230 ("app.attach.open", "Open Attachment…"), ("app.attach.reveal", "Show Attachment Folder"), ("app.attach.delete", "Delete Attachment…"),
1231 ("app.attach.delete-all", "Delete All Attachments…"), ("app.attach.sync", "Sync Attachments"),
1232 ("app.attach.set-directory", "Set Attachment Folder…"), ("app.attach.unset-directory", "Unset Attachment Folder"),
1233 ]
1234
1235 /// The commands and their keys, and why those that don't apply at the caret don't, worked
1236 /// out once when the palette opens rather than on every keystroke in the search field.
1237 @State private var rows: [CommandRow]?
1238
1239 var body: some View {
1240 CommandList(rows: rows ?? [], choose: choose)
1241 .onAppear {
1242 guard rows == nil else { return }
1243 rows = commandRows()
1244 }
1245 }
1246
1247 private func commandRows() -> [CommandRow] {
1248 let context = editor.editContext()
1249 let paneCommands: [(id: String, title: String)] = !panes ? [] : [("app.split-right", "Split Pane Right"), ("app.split-below", "Split Pane Below")]
1250 + (split ? [("app.pane-next", "Next Pane"), ("app.pane-close", "Close Pane"), ("app.pane-only", "Close Other Panes")] : [])
1251 return Self.commands(macros: editor.namedMacros, panes: paneCommands)
1252 // A user command's `when` leaves it out where it doesn't apply.
1253 .filter { UserCommands.shared.command($0.id)?.applies(in: context) ?? true }
1254 .map { command in
1255 CommandRow(id: command.id, title: CommandTitle.localized(command.title), keys: editor.keymap.keyLabels(for: command.id).first,
1256 reason: reason(command.id, context))
1257 }
1258 }
1259
1260 /// The commands listed, with English titles: `panes`, the editor's, and the named macros.
1261 static func commands(macros: NamedMacros, panes: [(id: String, title: String)] = []) -> [(id: String, title: String)] {
1262 var seen = Set<String>()
1263 return (panes + viewCommands + Commands.everything.map { ($0.id, $0.title) } + macros.names.map { (NamedMacros.commandPrefix + $0, $0) }
1264 + UserCommands.shared.all.map { ($0.id, $0.title) })
1265 .filter { !AppStoreCommands.hidden.contains($0.id) && offered($0.id) && seen.insert($0.id).inserted }
1266 }
1267
1268 /// Commands for a camera or scanner this device lacks aren't listed.
1269 private static func offered(_ id: String) -> Bool {
1270 switch id {
1271 case "app.attach.camera": CameraPicker.isAvailable
1272 case "app.attach.scan": DocumentScanner.isAvailable
1273 default: true
1274 }
1275 }
1276
1277 private func reason(_ id: String, _ context: EditContext) -> String? {
1278 switch id {
1279 case "app.recovery": return recoveries > 0 ? nil : String(localized: "No Recovery Versions")
1280 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")
1281 case "app.print-selection":
1282 return context.selection.contains { !$0.isEmpty } ? nil : String(localized: "No text is selected")
1283 case EditorScreen.exportSubtreeCommand, "app.share-subtree", "app.print-subtree":
1284 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")
1285 default: return editor.applies(id, in: context) ? nil : CommandReason.reason(for: id, in: context)
1286 }
1287 }
1288}
1289/// A table as CSV or TSV, for the save dialog.
1290struct TableFile: FileDocument {
1291 static var readableContentTypes: [UTType] { [.commaSeparatedText, .tabSeparatedText] }
1292 let text: String
1293 let type: UTType
1294
1295 init(text: String, type: UTType) {
1296 self.text = text
1297 self.type = type
1298 }
1299
1300 init(configuration: ReadConfiguration) throws {
1301 text = configuration.file.regularFileContents.map { String(decoding: $0, as: UTF8.self) } ?? ""
1302 type = configuration.contentType
1303 }
1304
1305 func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
1306 FileWrapper(regularFileWithContents: Data(text.utf8))
1307 }
1308}
1309/// A plotted table, as the Mac's plot sheet shows it.
1310struct PlotScreen: View {
1311 let plot: TablePlot.Plot
1312 @Environment(\.dismiss) private var dismiss
1313
1314 var body: some View {
1315 NavigationStack {
1316 PlotChart(plot)
1317 .navigationTitle("Plot")
1318 .navigationBarTitleDisplayMode(.inline)
1319 .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } }
1320 }
1321 }
1322}
1323/// A file from the photo picker, copied out of the picker's temporary place with its name.
1324struct PickedFile: Transferable {
1325 let url: URL
1326
1327 static var transferRepresentation: some TransferRepresentation {
1328 FileRepresentation(importedContentType: .item) { received in
1329 let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
1330 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
1331 let url = folder.appendingPathComponent(received.file.lastPathComponent)
1332 try FileManager.default.copyItem(at: received.file, to: url)
1333 return PickedFile(url: url)
1334 }
1335 }
1336}
1337
1338/// The passphrase sheet for org-crypt, its new text applied in the editor.
1339struct CryptScreen: View {
1340 let request: CryptRequest
1341 let session: DocumentSession
1342 let editor: MobileEditor?
1343 let report: (String) -> Void
1344 @Environment(\.dismiss) private var dismiss
1345
1346 var body: some View {
1347 NavigationStack {
1348 CryptSheet(request: request, session: session, text: { session.document(of: request.path)?.text ?? "" }, apply: apply) { message in
1349 dismiss()
1350 if let message { report(message) }
1351 }
1352 .navigationBarTitleDisplayMode(.inline)
1353 }
1354 }
1355
1356 private func apply(_ new: String) {
1357 guard let editor else { return }
1358 let context = editor.editContext()
1359 let caret = min(context.caret, (new as NSString).length)
1360 _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
1361 }
1362}
1363/// The pane an editor screen made for itself, closed with the screen.
1364@MainActor
1365final class PaneHolder {
1366 var pane: EditorPane?
1367 nonisolated(unsafe) var release: (() -> Void)?
1368
1369 deinit {
1370 guard let release else { return }
1371 Task { @MainActor in release() }
1372 }
1373}
1374
1375/// A command's result or refusal, over the screen until it is tapped or for four seconds, and
1376/// read out by VoiceOver.
1377private struct MessageView: ViewModifier {
1378 @Binding var message: String?
1379 let edge: VerticalEdge
1380
1381 func body(content: Content) -> some View {
1382 content.overlay(alignment: edge == .top ? .top : .bottom) {
1383 if let message {
1384 Text(message).font(.callout).multilineTextAlignment(.center)
1385 .padding(.horizontal, 14).padding(.vertical, 8)
1386 .glassEffect(.regular, in: .rect(cornerRadius: 18))
1387 .padding(8)
1388 .onTapGesture { self.message = nil }
1389 .task(id: message) {
1390 try? await Task.sleep(for: .seconds(4))
1391 if self.message == message { self.message = nil }
1392 }
1393 }
1394 }
1395 .onChange(of: message) { _, message in
1396 if let message { AccessibilityNotification.Announcement(message).post() }
1397 }
1398 }
1399}
1400
1401extension View {
1402 /// Shows `message` in the one message view, at the top or bottom of the screen.
1403 func message(_ message: Binding<String?>, edge: VerticalEdge = .bottom) -> some View {
1404 modifier(MessageView(message: message, edge: edge))
1405 }
1406}
1407
1408/// The screen's title, unless a split shows the focused pane's.
1409private struct EditorTitle: ViewModifier {
1410 let title: String
1411 let shown: Bool
1412
1413 func body(content: Content) -> some View {
1414 if shown {
1415 content.navigationTitle(title).navigationBarTitleDisplayMode(.inline)
1416 } else {
1417 content
1418 }
1419 }
1420}
1421#endif