Sources/OrgstarMobile/EditorScreen.swift

bd275bd1a81b85a03549d5435d6a0bd32c2cbd66
orgstar/Sources/OrgstarMobile/EditorScreen.swift

1444 lines · 74480 bytes

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