Sources/OrgstarMobile/EditorScreen.swift

7fee8f1214931d1d034bc40d1155a605813239cc
orgstar/Sources/OrgstarMobile/EditorScreen.swift

1125 lines · 57185 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)"
 618                if editor.showsImages { editor.restyleAll() }
 619            } else {
 620                sheet = .plot(plot)
 621            }
 622        } catch {
 623            message = "\(error)"
 624        }
 625    }
 626
 627    /// `org-table-export` of the table at the caret, as CSV or TSV.
 628    /// Words, characters and reading time of the selection, or of the file.
 629    private func wordCount() -> String {
 630        guard let editor else { return "No file is open" }
 631        let text = editor.document.text as NSString
 632        let selection = editor.textView.selectedRange
 633        let selected = selection.length > 0 && NSMaxRange(selection) <= text.length
 634        let counts = TextStats.region(selected ? text.substring(with: selection) : text as String)
 635        return (selected ? "Selection: " : "") + TextStats.summary(words: counts.words, characters: counts.characters)
 636    }
 637
 638    private func exportTable(csv: Bool) {
 639        guard let editor else { return }
 640        let context = editor.editContext()
 641        guard let text = ImportTable.exportText(context.text, at: context.caret, path: csv ? "table.csv" : "table.tsv") else {
 642            return message = "No table at point"
 643        }
 644        exportedTable = TableFile(text: text, type: csv ? .commaSeparatedText : .tabSeparatedText)
 645    }
 646
 647    /// `org-refile` of the entry at the caret, to a target worked out again from the files
 648    /// now, as the agenda's Refile… does.
 649    func refile(to target: RefileTarget, keep: Bool = false) {
 650        guard let editor, let path = session.path else { return }
 651        let caret = editor.editContext().caret
 652        guard let current = workspace.refileTargets(openPath: path, document: session.document).first(where: { $0.label == target.label }) else {
 653            message = "Can't find \(target.label) any more."
 654            return
 655        }
 656        message = session.refile(to: current, from: (path, caret), keep: keep)
 657    }
 658}
 659
 660/// The editor's text view, with the Org key bar over the keyboard.
 661struct EditorTextView: UIViewRepresentable {
 662    let editor: MobileEditor
 663    /// This pane's view of the editor.
 664    let view: UITextView
 665    let palette: () -> Void
 666
 667    func makeUIView(context: Context) -> UITextView {
 668        let bar = UIHostingController(rootView: KeyBar(editor: editor, palette: palette))
 669        bar.view.frame = CGRect(x: 0, y: 0, width: 400, height: 48)
 670        bar.view.backgroundColor = .clear
 671        bar.sizingOptions = []
 672        view.inputAccessoryView = bar.view
 673        context.coordinator.bar = bar
 674        return view
 675    }
 676
 677    func updateUIView(_ view: UITextView, context: Context) {}
 678
 679    func makeCoordinator() -> Coordinator { Coordinator() }
 680
 681    final class Coordinator {
 682        var bar: UIViewController?
 683    }
 684}
 685
 686/// Org's keys for a touch keyboard: each button does what its key does at the caret, as the
 687/// Emacs keymap binds it (M-→ demotes a heading, indents an item, moves a table column).
 688struct KeyBar: View {
 689    let editor: MobileEditor
 690    let palette: () -> Void
 691
 692    private static let keys: [(label: String, symbol: String?, keys: String)] = [
 693        ("Fold", "arrow.right.to.line", "TAB"),
 694        ("Overview", "arrow.left.to.line", "S-TAB"),
 695        ("Promote", "decrease.indent", "M-<left>"),
 696        ("Demote", "increase.indent", "M-<right>"),
 697        ("Move up", "arrow.up.square", "M-<up>"),
 698        ("Move down", "arrow.down.square", "M-<down>"),
 699        ("New heading or item", "plus", "M-RET"),
 700        ("TODO", nil, "C-c C-t"),
 701        ("Act at point", "checkmark.square", "C-c C-c"),
 702        ("Schedule", "calendar", "C-c C-s"),
 703        ("Deadline", "calendar.badge.exclamationmark", "C-c C-d"),
 704        ("Tags", "tag", "C-c C-q"),
 705        ("Open link", "link", "C-c C-o"),
 706    ]
 707
 708    /// Emphasis for the selection, or a pair of markers with the caret between.
 709    private static let emphasis: [(label: String, symbol: String, command: String)] = [
 710        ("Bold", "bold", "org.emphasize.bold"),
 711        ("Italic", "italic", "org.emphasize.italic"),
 712        ("Code", "chevron.left.forwardslash.chevron.right", "org.emphasize.code"),
 713    ]
 714
 715    var body: some View {
 716        ScrollView(.horizontal, showsIndicators: false) {
 717            HStack(spacing: 4) {
 718                Button("Commands", systemImage: "command", action: palette)
 719                ForEach(Self.keys, id: \.keys) { key in
 720                    Button {
 721                        editor.run(keys: key.keys)
 722                    } label: {
 723                        if let symbol = key.symbol { Label(key.label, systemImage: symbol) } else { Text(key.label).font(.callout.weight(.semibold)) }
 724                    }
 725                    .accessibilityLabel(key.label)
 726                }
 727                ForEach(Self.emphasis, id: \.command) { item in
 728                    Button(item.label, systemImage: item.symbol) { editor.run(item.command) }
 729                }
 730                Button("Hide keyboard", systemImage: "keyboard.chevron.compact.down") { editor.textView.resignFirstResponder() }
 731            }
 732            .labelStyle(.iconOnly)
 733            .buttonStyle(.bordered)
 734            .padding(.horizontal, 8)
 735            .padding(.vertical, 6)
 736        }
 737        .background(.bar)
 738    }
 739}
 740
 741/// A command's question: text with choices, a date, or fast selection by keys.
 742struct PromptSheet: View {
 743    let prompt: Prompt
 744    let answer: (String?) -> Void
 745    @State private var text = ""
 746    @State private var date = Date()
 747    @State private var withTime = false
 748    @State private var keys: [FastSelection.Input] = []
 749
 750    var body: some View {
 751        NavigationStack {
 752            Form {
 753                if let fast = prompt.fast {
 754                    fastSection(fast)
 755                } else {
 756                    Section {
 757                        TextField(prompt.message, text: $text)
 758                            .autocorrectionDisabled()
 759                            .textInputAutocapitalization(.never)
 760                            .onSubmit { answer(text) }
 761                    } footer: {
 762                        if prompt.date != nil { Text("Org's date syntax works too: +2d, fri, 14:00") }
 763                    }
 764                    if prompt.date != nil {
 765                        DatePicker("Date", selection: $date, displayedComponents: [.date])
 766                            .datePickerStyle(.graphical)
 767                            .onChange(of: date) { text = QuestionField.stamp(date, withTime: withTime) }
 768                        Toggle("Time", isOn: $withTime)
 769                            .onChange(of: withTime) {
 770                                if withTime { date = QuestionField.timed(date) }
 771                                text = QuestionField.stamp(date, withTime: withTime)
 772                            }
 773                        if withTime { DatePicker("Time", selection: $date, displayedComponents: .hourAndMinute) }
 774                    }
 775                    if !prompt.choices.isEmpty {
 776                        let matching = prompt.choices.filter { lastPart.isEmpty || $0.localizedCaseInsensitiveContains(lastPart) }
 777                        Section("Choices") {
 778                            ForEach(matching.prefix(50), id: \.self) { choice in
 779                                Button(choice) { choose(choice) }
 780                            }
 781                        }
 782                    }
 783                }
 784            }
 785            .navigationTitle(prompt.message.trimmingCharacters(in: CharacterSet(charactersIn: ": ")))
 786            .navigationBarTitleDisplayMode(.inline)
 787            .toolbar {
 788                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { answer(nil) } }
 789                if prompt.fast == nil || prompt.fast?.multiple == true {
 790                    ToolbarItem(placement: .confirmationAction) {
 791                        Button("Done") { answer(prompt.fast == nil ? text : FastSelection.encode(keys)) }
 792                            .disabled(prompt.requireMatch && prompt.fast == nil && !prompt.choices.isEmpty && !prompt.choices.contains(text))
 793                    }
 794                }
 795            }
 796        }
 797        .onAppear {
 798            text = prompt.initial
 799            date = prompt.date?.defaultDate ?? Calendar.current.startOfDay(for: Date())
 800        }
 801    }
 802
 803    /// With a separator (tags), what's typed after the last one.
 804    private var lastPart: String {
 805        guard let separator = prompt.completionSeparator else { return text }
 806        return String(text.split(separator: separator, omittingEmptySubsequences: false).last ?? "")
 807    }
 808
 809    private func choose(_ choice: String) {
 810        guard let separator = prompt.completionSeparator else {
 811            text = choice
 812            if prompt.date == nil { answer(choice) }
 813            return
 814        }
 815        var parts = text.split(separator: separator, omittingEmptySubsequences: false).map(String.init)
 816        if parts.isEmpty { parts = [""] }
 817        parts[parts.count - 1] = choice
 818        text = parts.joined(separator: String(separator)) + String(separator)
 819    }
 820
 821    @ViewBuilder
 822    private func fastSection(_ fast: FastSelection) -> some View {
 823        let current = fast.multiple ? fast.tags(after: keys) ?? [] : []
 824        Section {
 825            ForEach(Array(fast.options.enumerated()), id: \.offset) { _, option in
 826                Button {
 827                    if fast.multiple { keys.append(.key(option.key)) } else { answer(String(option.key)) }
 828                } label: {
 829                    HStack {
 830                        Text(option.name).foregroundStyle(.primary)
 831                        Spacer()
 832                        if current.contains(option.name) { Image(systemName: "checkmark") }
 833                        Text(String(option.key)).font(.caption.monospaced()).foregroundStyle(.secondary)
 834                    }
 835                }
 836            }
 837            if !fast.multiple {
 838                Button("No keyword") { answer(" ") }
 839            }
 840        } footer: {
 841            if fast.multiple, !fast.inherited.isEmpty { Text("Inherited: :" + fast.inherited.joined(separator: ":") + ":") }
 842        }
 843    }
 844}
 845
 846/// `org-edit-special` and `org-table-edit-field`: the text edited apart, put back with Save.
 847/// A src block's code is highlighted as its language.
 848struct BlockEditSheet: View {
 849    let edit: BlockEdit
 850    let theme: MobileTheme
 851    let finish: (String?) -> Void
 852    @State private var text: String?
 853
 854    var body: some View {
 855        NavigationStack {
 856            Group {
 857                if let text {
 858                    CodeTextView(text: text, language: edit.language, theme: theme) { self.text = $0 }
 859                }
 860            }
 861            .padding(.horizontal, 8)
 862            .navigationTitle(edit.title.replacingOccurrences(of: "Editing ", with: "").capitalized(with: nil))
 863            .navigationBarTitleDisplayMode(.inline)
 864            .toolbar {
 865                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { finish(nil) } }
 866                ToolbarItem(placement: .confirmationAction) { Button("Save") { finish(text ?? edit.content) } }
 867            }
 868        }
 869        .onAppear { text = edit.content }
 870    }
 871}
 872
 873/// A text view for code, restyled with the editor's highlighter after each change.
 874struct CodeTextView: UIViewRepresentable {
 875    let text: String
 876    let language: String?
 877    let theme: MobileTheme
 878    let changed: (String) -> Void
 879
 880    func makeUIView(context: Context) -> UITextView {
 881        let view = UITextView()
 882        view.autocorrectionType = .no
 883        view.autocapitalizationType = .none
 884        view.smartQuotesType = .no
 885        view.smartDashesType = .no
 886        view.spellCheckingType = .no
 887        view.keyboardDismissMode = .interactive
 888        view.backgroundColor = .clear
 889        view.text = text
 890        view.delegate = context.coordinator
 891        context.coordinator.style(view)
 892        DispatchQueue.main.async { view.becomeFirstResponder() }
 893        return view
 894    }
 895
 896    func updateUIView(_ view: UITextView, context: Context) {
 897        context.coordinator.parent = self
 898    }
 899
 900    func makeCoordinator() -> Coordinator { Coordinator(self) }
 901
 902    @MainActor
 903    final class Coordinator: NSObject, UITextViewDelegate {
 904        var parent: CodeTextView
 905        init(_ parent: CodeTextView) { self.parent = parent }
 906
 907        func textViewDidChange(_ view: UITextView) {
 908            parent.changed(view.text)
 909            style(view)
 910        }
 911
 912        /// The theme's font and color, then the language's token colors.
 913        func style(_ view: UITextView) {
 914            let storage = view.textStorage
 915            let whole = NSRange(location: 0, length: storage.length)
 916            let base: [NSAttributedString.Key: Any] = [.font: parent.theme.font, .foregroundColor: parent.theme.foreground]
 917            storage.beginEditing()
 918            storage.setAttributes(base, range: whole)
 919            if let language = parent.language {
 920                for run in MobileEditor.highlighter.highlights(language: language, code: storage.string) {
 921                    guard let key = run.category.themeKey, let color = parent.theme.color(key), run.range.upperBound <= storage.length else { continue }
 922                    storage.addAttribute(.foregroundColor, value: color, range: NSRange(location: run.range.lowerBound, length: run.range.count))
 923                }
 924            }
 925            storage.endEditing()
 926            view.typingAttributes = base
 927        }
 928    }
 929}
 930
 931/// Every command that applies at the caret, by name.
 932struct CommandPalette: View {
 933    let editor: MobileEditor
 934    /// The pane commands are offered (on iPad), and those for more than one pane.
 935    var panes = false
 936    var split = false
 937    /// Called with the chosen command before the palette closes.
 938    let choose: (String) -> Void
 939    @State private var query = ""
 940    @Environment(\.dismiss) private var dismiss
 941
 942    private static let viewCommands: [(id: String, title: String)] = [
 943        ("org.cycle", "Cycle Visibility"), ("org.cycle-global", "Cycle Global Visibility"),
 944        ("edit.undo", "Undo"), ("edit.redo", "Redo"),
 945        ("app.clock.in", "Clock In"), ("app.clock.out", "Clock Out"), ("app.clock.cancel", "Cancel Clock"),
 946        ("app.clock.goto", "Go to Clocked Entry"), ("app.clock.in-recent", "Clock In to Recent Entry…"),
 947        ("app.clock.in-last", "Clock In to Last Entry"), ("app.clock.goto-recent", "Go to Recent Clocked Entry…"),
 948        ("app.clock.default", "Mark as Default Clock Task"), ("app.clock.resolve", "Resolve Open Clocks…"),
 949        ("app.refile", "Refile…"), ("app.refile.copy", "Copy to Refile Target…"), ("app.refile.goto", "Go to Refile Target…"),
 950        ("app.toggle-markup", "Show or Hide Markup"),
 951        ("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"),
 952        ("edit.isearch-forward", "Incremental Search"), ("edit.isearch-backward", "Incremental Search Backward"),
 953        ("org.table.toggle-column-width", "Shrink or Expand Table Column"), ("org.table.shrink", "Shrink Table Columns with Widths"),
 954        ("org.table.expand", "Expand Table Columns"),
 955        ("app.table-import", "Import Table from File…"), ("app.table-export", "Export Table to File…"), ("app.plot", "Plot Table"),
 956        ("app.crypt.encrypt-entry", "Encrypt Entry…"), ("app.crypt.open-entry", "Decrypt Entry…"), ("app.crypt.decrypt-entry", "Decrypt Entry in File…"),
 957        ("app.crypt.encrypt-entries", "Encrypt Tagged Entries…"), ("app.crypt.forget-passphrase", "Forget Encryption Passphrase"),
 958        ("app.backlinks", "Show Backlinks"), ("app.node.find", "Find Node…"), ("app.node.insert", "Insert Node Link…"),
 959        ("app.node.rename-from-front-matter", "Rename Note from Front Matter"),
 960        ("app.node.rename", "Rename Note…"),
 961        ("app.node.rename-folder-from-front-matter", "Rename Notes in Folder from Front Matter…"),
 962        ("app.node.silo-find", "Find Note in Silo…"),
 963        ("app.node.silo-create", "New Note in Silo…"),
 964        ("app.node.sequence-new-parent", "New Sequence Note…"),
 965        ("app.node.sequence-new-child", "New Child Sequence Note…"),
 966        ("app.node.sequence-new-sibling", "New Sibling Sequence Note…"),
 967        ("app.node.sequence-new-child-of-current", "New Child of This Note…"),
 968        ("app.node.sequence-new-sibling-of-current", "New Sibling of This Note…"),
 969        ("app.node.sequence-find", "Find Sequence Relatives…"),
 970        ("app.node.sequence-next-sibling", "Next Sibling Note"),
 971        ("app.node.sequence-previous-sibling", "Previous Sibling Note"),
 972        ("app.node.sequence-reparent", "Reparent Note…"),
 973        ("app.node.sequence-reparent-recursive", "Reparent Note with Descendants…"),
 974        ("app.node.sequence-rename-as-parent", "Rename Note as Sequence Parent"),
 975        ("app.node.sequence-convert", "Convert Note Sequence Scheme"),
 976        ("app.node.sequence-link", "Insert Sequence Link…"),
 977        ("app.node.sequence-hierarchy", "Sequence Hierarchy…"),
 978        ("app.dailies.today", "Go to Today's Daily Note"), ("app.dailies.yesterday", "Go to Yesterday's Daily Note"),
 979        ("app.dailies.tomorrow", "Go to Tomorrow's Daily Note"), ("app.dailies.date", "Go to Daily Note for Date…"),
 980        ("app.dailies.capture-today", "Capture to Today's Daily Note"), ("app.dailies.capture-yesterday", "Capture to Yesterday's Daily Note"),
 981        ("app.dailies.capture-tomorrow", "Capture to Tomorrow's Daily Note"), ("app.dailies.capture-date", "Capture to Daily Note for Date…"),
 982        ("app.dailies.next", "Next Daily Note"), ("app.dailies.previous", "Previous Daily Note"),
 983        ("app.attach.attach", "Attach File…"), ("app.attach.url", "Attach File from URL…"), ("app.attach.new", "New Attachment…"),
 984        ("app.attach.open", "Open Attachment…"), ("app.attach.reveal", "Show Attachment Folder"), ("app.attach.delete", "Delete Attachment…"),
 985        ("app.attach.delete-all", "Delete All Attachments…"), ("app.attach.sync", "Sync Attachments"),
 986        ("app.attach.set-directory", "Set Attachment Folder…"), ("app.attach.unset-directory", "Unset Attachment Folder"),
 987    ]
 988
 989    /// The commands that apply at the caret and their keys, worked out once when the palette
 990    /// opens rather than on every keystroke in the search field.
 991    @State private var applicable: [(id: String, title: String, keys: String?)]?
 992
 993    var body: some View {
 994        let shown = (applicable ?? []).filter { query.isEmpty || $0.title.localizedCaseInsensitiveContains(query) }
 995        NavigationStack {
 996            List(shown, id: \.id) { command in
 997                Button {
 998                    choose(command.id)
 999                    dismiss()
1000                } label: {
1001                    HStack {
1002                        Text(command.title).foregroundStyle(.primary)
1003                        Spacer()
1004                        if let keys = command.keys {
1005                            Text(keys).font(.caption.monospaced()).foregroundStyle(.secondary)
1006                        }
1007                    }
1008                }
1009            }
1010            .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always))
1011            .navigationTitle("Commands")
1012            .navigationBarTitleDisplayMode(.inline)
1013            .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Close") { dismiss() } } }
1014        }
1015        .onAppear {
1016            guard applicable == nil else { return }
1017            let context = editor.editContext()
1018            let paneCommands: [(id: String, title: String)] = !panes ? [] : [("app.split-right", "Split Pane Right"), ("app.split-below", "Split Pane Below")]
1019                + (split ? [("app.pane-next", "Next Pane"), ("app.pane-close", "Close Pane"), ("app.pane-only", "Close Other Panes")] : [])
1020            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) })
1021                .filter { editor.applies($0.id, in: context) }
1022                .map { ($0.id, CommandTitle.localized($0.title), editor.keymap.keyLabels(for: $0.id).first) }
1023        }
1024    }
1025}
1026/// A table as CSV or TSV, for the save dialog.
1027struct TableFile: FileDocument {
1028    static var readableContentTypes: [UTType] { [.commaSeparatedText, .tabSeparatedText] }
1029    let text: String
1030    let type: UTType
1031
1032    init(text: String, type: UTType) {
1033        self.text = text
1034        self.type = type
1035    }
1036
1037    init(configuration: ReadConfiguration) throws {
1038        text = configuration.file.regularFileContents.map { String(decoding: $0, as: UTF8.self) } ?? ""
1039        type = configuration.contentType
1040    }
1041
1042    func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
1043        FileWrapper(regularFileWithContents: Data(text.utf8))
1044    }
1045}
1046/// A plotted table, as the Mac's plot sheet shows it.
1047struct PlotScreen: View {
1048    let plot: TablePlot.Plot
1049    @Environment(\.dismiss) private var dismiss
1050
1051    var body: some View {
1052        NavigationStack {
1053            PlotChart(plot)
1054                .navigationTitle("Plot")
1055                .navigationBarTitleDisplayMode(.inline)
1056                .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } }
1057        }
1058    }
1059}
1060/// A file from the photo picker, copied out of the picker's temporary place with its name.
1061struct PickedFile: Transferable {
1062    let url: URL
1063
1064    static var transferRepresentation: some TransferRepresentation {
1065        FileRepresentation(importedContentType: .item) { received in
1066            let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
1067            try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
1068            let url = folder.appendingPathComponent(received.file.lastPathComponent)
1069            try FileManager.default.copyItem(at: received.file, to: url)
1070            return PickedFile(url: url)
1071        }
1072    }
1073}
1074
1075/// The passphrase sheet for org-crypt, its new text applied in the editor.
1076struct CryptScreen: View {
1077    let request: CryptRequest
1078    let session: DocumentSession
1079    let editor: MobileEditor?
1080    let report: (String) -> Void
1081    @Environment(\.dismiss) private var dismiss
1082
1083    var body: some View {
1084        NavigationStack {
1085            CryptSheet(request: request, text: { session.document?.text ?? "" }, apply: apply) { message in
1086                dismiss()
1087                if let message { report(message) }
1088            }
1089            .navigationBarTitleDisplayMode(.inline)
1090        }
1091    }
1092
1093    private func apply(_ new: String) {
1094        guard let editor else { return }
1095        let context = editor.editContext()
1096        let caret = min(context.caret, (new as NSString).length)
1097        _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
1098    }
1099}
1100/// The pane an editor screen made for itself, closed with the screen.
1101@MainActor
1102final class PaneHolder {
1103    var pane: EditorPane?
1104    nonisolated(unsafe) var release: (() -> Void)?
1105
1106    deinit {
1107        guard let release else { return }
1108        Task { @MainActor in release() }
1109    }
1110}
1111
1112/// The screen's title, unless a split shows the focused pane's.
1113private struct EditorTitle: ViewModifier {
1114    let title: String
1115    let shown: Bool
1116
1117    func body(content: Content) -> some View {
1118        if shown {
1119            content.navigationTitle(title).navigationBarTitleDisplayMode(.inline)
1120        } else {
1121            content
1122        }
1123    }
1124}
1125#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