Sources/OrgstarMobile/EditorScreen.swift

525225e4f44b53a1ea7559b03462473575dfa523
orgstar/Sources/OrgstarMobile/EditorScreen.swift

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