Sources/OrgstarMobile/EditorScreen.swift

73b5c3d29343d6a3801f3a9a591fa434c01c9f06
orgstar/Sources/OrgstarMobile/EditorScreen.swift

1453 lines · 74921 bytes

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form