Sources/OrgstarMobile/EditorScreen.swift

2df4420ff51f7e97a9c06eacf814f64cdb5a4351
orgstar/Sources/OrgstarMobile/EditorScreen.swift

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