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