Sources/OrgstarMobile/EditorScreen.swift

4b0ad76c9ca64e32a6c95a891e8db59bacbf81af
orgstar/Sources/OrgstarMobile/EditorScreen.swift

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