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