Sources/OrgstarMobile/EditorScreen.swift

fc3ddfcd5858fab2b88399e3df1ce76f3213a7c9
orgstar/Sources/OrgstarMobile/EditorScreen.swift

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