Sources/OrgstarMobile/EditorScreen.swift

7f0c7bf3c773402711ac74c8f850bf858319580f
orgstar/Sources/OrgstarMobile/EditorScreen.swift

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