Sources/OrgstarMobile/EditorScreen.swift

7d137d1b02ef553e996f782b56fafc59026c759f
orgstar/Sources/OrgstarMobile/EditorScreen.swift

1345 lines · 69900 bytes

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