Sources/OrgstarMobile/EditorScreen.swift

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