Sources/OrgstarMobile/EditorScreen.swift

4d8e517de5aef10e915fb482735feba5435a4a21
orgstar/Sources/OrgstarMobile/EditorScreen.swift

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