Sources/OrgstarMobile/EditorScreen.swift

design-themes-widgets
orgstar/Sources/OrgstarMobile/EditorScreen.swift history · blame · raw

1277 lines · 66168 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 tree = session.document(of: path)?.tree {
 193                        ExportMenu(path: path, tree: tree, 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 tree = session.document(of: path)?.tree { SubtreeExportScreen(path: path, tree: tree, 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.fileName = path
 456        editor.attachmentPath = { DocumentSession.attachmentPath($0, at: $1, tree: $2, path: path) }
 457        return editor
 458    }
 459
 460    /// The editor's callbacks go to this screen: it's shown here, or its view here took focus.
 461    private func bind(_ editor: MobileEditor) {
 462        editor.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] }
 463        editor.onChange = { [weak session] in session?.bufferChanged(path) }
 464        editor.onMessage = { message = $0 }
 465        editor.onPrompt = { prompt, reply in self.prompt = PromptRequest(prompt: prompt, reply: reply) }
 466        editor.onLink = { link in follow(link) }
 467        editor.onEditBlock = { edit in sheet = .block(edit) }
 468        editor.onColumnView = { view in sheet = .columns(view) }
 469        editor.onTangle = { scope in if ProAccess.shared.allows(.babel) { message = session.tangle(scope) } }
 470        editor.onBabel = { job in if ProAccess.shared.allows(.babel) { run(job) } }
 471        editor.onRefreshSetup = { session.refreshSetup() }
 472        editor.onAgenda = { start, count in model.agendaRequest = .init(start: start, count: count) }
 473        editor.keymap = model.keymap
 474        editor.modal = model.modalKeys
 475        // Dropped files are copies the drop made, so they are attached, not linked or opened.
 476        editor.onFiles = { attachActions.drop($0, method: .attach, attachMethod: .mv) }
 477        editor.onImage = { attachActions.yankImage($0, ext: $1) }
 478        editor.onAppCommand = { id in
 479            if let feature = ProFeature.required(byCommand: id), !ProAccess.shared.allows(feature) { return }
 480            if Self.paneCommands.contains(id) {
 481                if let onPaneCommand { onPaneCommand(id) } else { message = "Not available here" }
 482            } else if id == "app.save" {
 483                _ = session.save(path)
 484            } else if id == "app.archive" {
 485                if let caret = self.editor?.editContext().caret { message = session.archive(from: (path, caret)) }
 486            } else if id == "app.copy-rich-text" {
 487                if let text = session.document(of: path)?.text { message = ExportMenu.copy(path: path, text: text, theme: model.theme) }
 488            } else if id == "app.export.html-open" {
 489                exportHTMLAndOpen()
 490            } else if id == "app.export-body-only" {
 491                let on = !ExportSettings.saved(for: path).bodyOnly
 492                ExportMenu.setBodyOnly(on, path: path)
 493                message = on ? "Export: body only" : "Export: whole document"
 494            } else if id == "app.export.icalendar-agenda" || id == "app.export.icalendar-combined" {
 495                agendaCalendars(combined: id == "app.export.icalendar-combined")
 496            } else if id.hasPrefix("app.publish") {
 497                publish(id)
 498            } else if AppStoreCommands.unavailable(id) {
 499                message = "Attachments can't be linked on iPhone and iPad; Attach File… copies the file."
 500            } else if ["app.refile", "app.refile.copy", "app.refile.goto"].contains(id) {
 501                sheet = .refile(id)
 502            } else if id == "app.table-import" {
 503                importingTable = true
 504            } else if id == "app.table-export" {
 505                exportTable(csv: true)
 506            } else if id == "app.plot" {
 507                plotTable()
 508            } else if id.hasPrefix("app.crypt.") {
 509                crypt(id)
 510            } else if id.hasPrefix("app.attach.") {
 511                attachActions.run(id)
 512            } else if id == "app.node.graph" {
 513                sheet = .graph
 514            } else if id.hasPrefix("app.dailies.") || id.hasPrefix("app.node.") {
 515                roamActions.run(id)
 516            } else if id == "app.backlinks" {
 517                sheet = .backlinks
 518            } else if id == "app.toggle-markup" {
 519                model.showMarkup.toggle()
 520            } else if MobileEditor.linkCommands.contains(id) {
 521                link(id)
 522            } else if !MobileClock.run(id, model: model, workspace: workspace, show: { message = $0 }) {
 523                message = "Not available on iOS yet"
 524            }
 525        }
 526    }
 527}
 528
 529extension EditorScreen {
 530    /// Follows a link; files the editor doesn't open show in Quick Look.
 531    private func follow(_ link: OrgLink) {
 532        switch session.follow(link, workspace: workspace, isText: { _ in false }) {
 533        case .shown:
 534            // A link to another file shows it on its own screen; this pane keeps its file.
 535            guard let pane, let target = pane.path, target != path else { message = nil; return }
 536            let caret = session.caret(of: target) ?? 0
 537            session.open(path, in: pane)
 538            model.openRequest = .offset(target, caret)
 539        case .openExternally(let url): if url.isFileURL { previewed = url } else { openURL(url) }
 540        case .message(let text): message = text
 541        case .choose(let question, let paths):
 542            let labels = paths.map { ($0 as NSString).lastPathComponent }
 543            prompt = PromptRequest(prompt: Prompt(key: "file", message: question, choices: labels)) { answer in
 544                guard let answer, let index = labels.firstIndex(of: answer) else { return }
 545                follow(OrgLink(type: "file", path: paths[index], raw: "file:" + paths[index]))
 546            }
 547        case .elisp(let form):
 548            // Once trusted, as `org-link-elisp-confirm-function` asks.
 549            let go = { _ = Task { message = await session.evaluateLink(form) } }
 550            let content = "elisp:" + form
 551            if trust.isTrusted(path: path, content: content) { return go() }
 552            prompt = PromptRequest(prompt: Prompt(key: "confirm", message: "Execute \(form) as Elisp?", choices: ["yes", "no", "always"])) { answer in
 553                switch answer {
 554                case "always":
 555                    trust.trust(path: path, content: content)
 556                    go()
 557                case "yes": go()
 558                default: message = "Not run"
 559                }
 560            }
 561        }
 562    }
 563
 564    /// org-roam's daily notes and nodes.
 565    private var roamActions: RoamActions {
 566        RoamActions(
 567            session: session, roots: { workspace.rootPaths },
 568            nodes: { try workspace.nodes(overlay: workspace.overlay(session.openDocuments)) },
 569            show: { message = $0 }, ask: { prompt = PromptRequest(prompt: $0, reply: $1) },
 570            open: { file, offset in
 571                if file == path { editor?.reveal(offset) } else { model.openRequest = .offset(file, offset) }
 572            },
 573            insertLink: { link, title in
 574                guard let editor else { return }
 575                let context = editor.editContext()
 576                let range = context.selection.first ?? context.caret..<context.caret
 577                let selected = (context.text as NSString).substring(with: NSRange(range))
 578                let text = Links.makeString(link, selected.isEmpty ? title : selected)
 579                let end = range.lowerBound + (text as NSString).length
 580                _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: [TextEdit(range: range, replacement: text)], selection: [end..<end])))
 581            },
 582            refresh: { Task { await workspace.refresh() } })
 583    }
 584
 585    /// org-attach's commands for the entry at the caret.
 586    private var attachActions: AttachActions {
 587        AttachActions(
 588            entry: {
 589                guard let editor else { return nil }
 590                let context = editor.editContext()
 591                return Attachments.Entry(text: context.text, offset: context.caret, path: path, options: context.options)
 592            },
 593            apply: { new, caret in
 594                guard let editor else { return }
 595                let context = editor.editContext()
 596                let caret = min(caret ?? context.caret, (new as NSString).length)
 597                _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
 598            },
 599            show: { message = $0 },
 600            ask: { prompt = PromptRequest(prompt: $0, reply: $1) },
 601            storeLink: { _ = StoredLink.add($0, to: &model.storedLinks) },
 602            open: { follow(OrgLink(type: "file", path: $0, raw: "file:" + $0)) },
 603            reveal: { dir in
 604                if let url = URL(string: "shareddocuments://" + (dir.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? dir)) { openURL(url) }
 605            },
 606            pick: { attaching = $0 })
 607    }
 608
 609    /// Photos and videos attached under the names Photos gives them, linked at the caret.
 610    private func attachPhotos(_ items: [PhotosPickerItem]) {
 611        Task { @MainActor in
 612            var urls: [URL] = []
 613            for item in items {
 614                if let picked = try? await item.loadTransferable(type: PickedFile.self) { urls.append(picked.url) }
 615            }
 616            if urls.count < items.count { message = "Can't read \(items.count - urls.count) of the items" }
 617            if !urls.isEmpty { attachActions.drop(urls, method: .attach, attachMethod: .mv) }
 618        }
 619    }
 620
 621    /// `org-table-import`: a TSV, CSV or space-separated file becomes a table at the caret.
 622    private func importTable(_ result: Result<URL, Error>) {
 623        guard case .success(let url) = result, let editor else { return }
 624        let scoped = url.startAccessingSecurityScopedResource()
 625        defer { if scoped { url.stopAccessingSecurityScopedResource() } }
 626        guard let contents = try? String(contentsOf: url, encoding: .utf8) else { return message = "Can't read \(url.lastPathComponent)" }
 627        _ = editor.perform(ImportTable(contents: contents))
 628    }
 629
 630    /// The export formats for the subtree at the caret, as the Mac's export sheet's scope.
 631    private func exportSubtree() {
 632        guard let context = editor?.editContext() else { return }
 633        guard ExportScope.subtree(context.text, at: context.caret) != nil else { return message = "Not in a subtree" }
 634        sheet = .exportSubtree(context.caret)
 635    }
 636
 637    /// `org-html-export-to-html` and open: the page in Quick Look, from a temporary file.
 638    private func exportHTMLAndOpen() {
 639        guard let text = session.document(of: path)?.text else { return }
 640        let html = OrgExport.html(text, path: path, theme: model.theme, bodyOnly: ExportSettings.saved(for: path).bodyOnly)
 641        let name = ExportScope.output(for: URL(fileURLWithPath: path), name: ExportScope.fileName(text, settings: OrgPreferences.orgSettings()), extension: "html")
 642            .lastPathComponent
 643        do {
 644            previewed = try HTMLPreview.write(html, directory: URL(fileURLWithPath: path).deletingLastPathComponent(), name: name)
 645        } catch {
 646            message = "Can't export \(name): \(error.localizedDescription)"
 647        }
 648    }
 649
 650    /// The agenda files' calendars written beside them, or combined in one shown in Quick Look,
 651    /// whose share button saves or sends it.
 652    private func agendaCalendars(combined: Bool) {
 653        guard let calendars = AgendaCalendars(model: model) else { return message = "No agenda files" }
 654        guard combined else { return message = calendars.exportEach() }
 655        do {
 656            previewed = try calendars.combined()
 657        } catch {
 658            message = "Can't export: \(error.localizedDescription)"
 659        }
 660    }
 661
 662    /// `org-publish` and its variants, for the `[[publish]]` projects in config.toml.
 663    private func publish(_ id: String) {
 664        guard let all = publishProjects() else { return }
 665        let current = Publish.projects(containing: path, in: all)
 666        switch id {
 667        case "app.publish.all":
 668            publish(all.map(\.name))
 669        case "app.publish.current-file":
 670            guard let project = current.first else { return message = "File is not part of any known project" }
 671            publish([project.name], only: path)
 672        case "app.publish.current-project":
 673            guard let project = current.first else { return message = "File is not part of any known project" }
 674            publish([project.name])
 675        default:
 676            prompt = PromptRequest(prompt: Prompt(key: "project", message: "Publish project:", choices: all.map(\.name))) { answer in
 677                if let answer, all.contains(where: { $0.name == answer }) { publish([answer]) }
 678            }
 679        }
 680    }
 681
 682    /// The projects in config.toml, each publishing to the folder chosen for it; nil, with a
 683    /// message, when there are none.
 684    private func publishProjects() -> [PublishProject]? {
 685        let config = (try? String(contentsOf: UserConfig.file("config.toml"), encoding: .utf8)) ?? ""
 686        let loaded = Publish.projects(fromConfig: config, root: workspace.rootPaths.first)
 687        if let problem = loaded.problems.first { message = problem }
 688        guard !loaded.projects.isEmpty else {
 689            message = "No [[publish]] projects in config.toml"
 690            return nil
 691        }
 692        return PublishFolders.shared.applied(to: loaded.projects)
 693    }
 694
 695    /// Publishes the projects named, `only` that file when given. A project that publishes
 696    /// outside the folders added to orgstar asks for its folder first, once.
 697    private func publish(_ names: [String], only: String? = nil) {
 698        guard let all = publishProjects() else { return }
 699        let chosen = all.filter { names.contains($0.name) }
 700        do {
 701            if let project = try PublishFolders.shared.needed(chosen, all: all, roots: workspace.rootPaths).first {
 702                message = "Choose the folder \(project.name) publishes to"
 703                publishFolder = PublishFolderRequest(project: project.name) { publish(names, only: only) }
 704                choosingPublishFolder = true
 705                return
 706            }
 707            if let project = try Publish.expand(chosen, all: all).first(where: { !FileManager.default.fileExists(atPath: $0.baseDirectory) }) {
 708                return message = "Can't read \(project.name)'s base-directory, \(OrgPaths.abbreviatingWithTilde(project.baseDirectory))"
 709            }
 710            let read = { (file: String) -> String? in
 711                session.openDocuments.first { $0.path == file }?.document.text ?? (try? String(contentsOfFile: file, encoding: .utf8))
 712            }
 713            let codeStyle = HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme)
 714            // As the Export menu: no author unless the file has #+AUTHOR:.
 715            let report = try Publish.publish(chosen, all: all, only: only, author: "", read: read) { function, text, file, bodyOnly in
 716                try Publish.export(function, text: text, path: file, bodyOnly: bodyOnly, settings: OrgPreferences.orgSettings(), codeStyle: codeStyle, author: "")
 717            }
 718            message = "Published \(report.published.count) files" + (report.skipped.isEmpty ? "" : ", \(report.skipped.count) up to date")
 719        } catch {
 720            message = "\(error)"
 721        }
 722    }
 723
 724    /// Org-roam's commands, with Pro.
 725    private func roam(_ id: String) {
 726        if ProAccess.shared.allows(.roam) { roamActions.run(id) }
 727    }
 728
 729    /// org-crypt's commands at the caret, through the passphrase sheet.
 730    private func crypt(_ id: String) {
 731        if let feature = ProFeature.required(byCommand: id), !ProAccess.shared.allows(feature) { return }
 732        guard let editor else { return }
 733        let context = editor.editContext()
 734        switch id {
 735        case "app.crypt.forget-passphrase":
 736            CryptPassphrases.forget(path)
 737            message = "Passphrase forgotten for \((path as NSString).lastPathComponent)"
 738        case "app.crypt.encrypt-entries":
 739            sheet = .crypt(CryptRequest(mode: .encryptAll(tag: OrgPreferences.cryptTag()), path: path, offset: context.caret))
 740        default:
 741            guard OrgCrypt.heading(context.text, at: context.caret) != nil else { return message = "Before first headline" }
 742            let encrypted = OrgCrypt.encryptedRange(context.text, at: context.caret) != nil
 743            if id == "app.crypt.encrypt-entry" {
 744                guard !encrypted else { return message = "The entry is encrypted already" }
 745                sheet = .crypt(CryptRequest(mode: .encrypt, path: path, offset: context.caret))
 746            } else {
 747                guard encrypted else { return message = "Not an encrypted entry" }
 748                sheet = .crypt(CryptRequest(mode: id == "app.crypt.open-entry" ? .open : .decryptInPlace, path: path, offset: context.caret))
 749            }
 750        }
 751    }
 752
 753    /// `org-plot/gnuplot`, drawn by Swift Charts: written to `file:` when the options name
 754    /// one, else shown.
 755    private func plotTable() {
 756        guard let editor else { return }
 757        let context = editor.editContext()
 758        do {
 759            let plot = try TablePlot.plot(context.text, at: context.caret)
 760            if let url = PlotOutput.file(plot, directory: URL(fileURLWithPath: path).deletingLastPathComponent()) {
 761                try PlotOutput.write(plot, to: url)
 762                message = "Plot written to \(url.lastPathComponent)" + (PlotOutput.note(plot).map { ". " + $0 } ?? "")
 763                if editor.showsImages { editor.restyleAll() }
 764            } else {
 765                try PlotOutput.check(plot)
 766                sheet = .plot(plot)
 767                if let note = PlotOutput.note(plot) { message = note }
 768            }
 769        } catch {
 770            message = "\(error)"
 771        }
 772    }
 773
 774    /// `org-table-export` of the table at the caret, as CSV or TSV.
 775    /// Words, characters and reading time of the selection, or of the file.
 776    private func wordCount() -> String {
 777        guard let editor else { return "No file is open" }
 778        let text = editor.document.text as NSString
 779        let selection = editor.textView.selectedRange
 780        let selected = selection.length > 0 && NSMaxRange(selection) <= text.length
 781        let counts = TextStats.region(selected ? text.substring(with: selection) : text as String)
 782        return (selected ? "Selection: " : "") + TextStats.summary(words: counts.words, characters: counts.characters)
 783    }
 784
 785    private func exportTable(csv: Bool) {
 786        guard let editor else { return }
 787        let context = editor.editContext()
 788        guard let text = ImportTable.exportText(context.text, at: context.caret, path: csv ? "table.csv" : "table.tsv") else {
 789            return message = "No table at point"
 790        }
 791        exportedTable = TableFile(text: text, type: csv ? .commaSeparatedText : .tabSeparatedText)
 792    }
 793
 794    /// `org-refile` of the entry at the caret, to a target worked out again from the files
 795    /// now, as the agenda's Refile… does.
 796    func refile(to target: RefileTarget, keep: Bool = false) {
 797        guard let editor, let path = session.path else { return }
 798        let caret = editor.editContext().caret
 799        guard let current = workspace.refileTargets(openPath: path, document: session.document).first(where: { $0.label == target.label }) else {
 800            message = "Can't find \(target.label) any more."
 801            return
 802        }
 803        message = session.refile(to: current, from: (path, caret), keep: keep)
 804    }
 805}
 806
 807/// The editor's text view, with the Org key bar over the keyboard.
 808struct EditorTextView: UIViewRepresentable {
 809    let editor: MobileEditor
 810    /// This pane's view of the editor.
 811    let view: UITextView
 812    let palette: () -> Void
 813
 814    func makeUIView(context: Context) -> UITextView {
 815        let bar = UIHostingController(rootView: KeyBar(editor: editor, palette: palette))
 816        bar.view.frame = CGRect(x: 0, y: 0, width: 400, height: 48)
 817        bar.view.backgroundColor = .clear
 818        bar.sizingOptions = []
 819        view.inputAccessoryView = bar.view
 820        context.coordinator.bar = bar
 821        return view
 822    }
 823
 824    func updateUIView(_ view: UITextView, context: Context) {}
 825
 826    func makeCoordinator() -> Coordinator { Coordinator() }
 827
 828    final class Coordinator {
 829        var bar: UIViewController?
 830    }
 831}
 832
 833/// Org's keys for a touch keyboard: each button does what its key does at the caret, as the
 834/// Emacs keymap binds it (M-→ demotes a heading, indents an item, moves a table column).
 835struct KeyBar: View {
 836    let editor: MobileEditor
 837    let palette: () -> Void
 838
 839    private static let keys: [(label: String, symbol: String?, keys: String)] = [
 840        ("Fold", "arrow.right.to.line", "TAB"),
 841        ("Overview", "arrow.left.to.line", "S-TAB"),
 842        ("Promote", "decrease.indent", "M-<left>"),
 843        ("Demote", "increase.indent", "M-<right>"),
 844        ("Move up", "arrow.up.square", "M-<up>"),
 845        ("Move down", "arrow.down.square", "M-<down>"),
 846        ("New heading or item", "plus", "M-RET"),
 847        ("TODO", nil, "C-c C-t"),
 848        ("Act at point", "checkmark.square", "C-c C-c"),
 849        ("Schedule", "calendar", "C-c C-s"),
 850        ("Deadline", "calendar.badge.exclamationmark", "C-c C-d"),
 851        ("Tags", "tag", "C-c C-q"),
 852        ("Open link", "link", "C-c C-o"),
 853    ]
 854
 855    /// Emphasis for the selection, or a pair of markers with the caret between.
 856    private static let emphasis: [(label: String, symbol: String, command: String)] = [
 857        ("Bold", "bold", "org.emphasize.bold"),
 858        ("Italic", "italic", "org.emphasize.italic"),
 859        ("Code", "chevron.left.forwardslash.chevron.right", "org.emphasize.code"),
 860    ]
 861
 862    var body: some View {
 863        ScrollView(.horizontal, showsIndicators: false) {
 864            HStack(spacing: 4) {
 865                Button("Commands", systemImage: "command", action: palette)
 866                ForEach(Self.keys, id: \.keys) { key in
 867                    Button {
 868                        editor.run(keys: key.keys)
 869                    } label: {
 870                        if let symbol = key.symbol { Label(key.label, systemImage: symbol) } else { Text(key.label).font(.callout.weight(.semibold)) }
 871                    }
 872                    .accessibilityLabel(key.label)
 873                }
 874                ForEach(Self.emphasis, id: \.command) { item in
 875                    Button(item.label, systemImage: item.symbol) { editor.run(item.command) }
 876                }
 877                Button("Hide keyboard", systemImage: "keyboard.chevron.compact.down") { editor.textView.resignFirstResponder() }
 878            }
 879            .labelStyle(.iconOnly)
 880            .buttonStyle(.bordered)
 881            .padding(.horizontal, 8)
 882            .padding(.vertical, 6)
 883        }
 884        .background(.bar)
 885    }
 886}
 887
 888/// A command's question: text with choices, a date, or fast selection by keys.
 889struct PromptSheet: View {
 890    let prompt: Prompt
 891    let answer: (String?) -> Void
 892    @State private var text = ""
 893    @State private var date = Date()
 894    @State private var withTime = false
 895    @State private var keys: [FastSelection.Input] = []
 896
 897    var body: some View {
 898        NavigationStack {
 899            Form {
 900                if let fast = prompt.fast {
 901                    fastSection(fast)
 902                } else {
 903                    Section {
 904                        TextField(prompt.message, text: $text)
 905                            .autocorrectionDisabled()
 906                            .textInputAutocapitalization(.never)
 907                            .onSubmit { answer(text) }
 908                    } footer: {
 909                        if prompt.date != nil { Text("Org's date syntax works too: +2d, fri, 14:00") }
 910                    }
 911                    if prompt.date != nil {
 912                        DatePicker("Date", selection: $date, displayedComponents: [.date])
 913                            .datePickerStyle(.graphical)
 914                            .onChange(of: date) { text = QuestionField.stamp(date, withTime: withTime) }
 915                        Toggle("Time", isOn: $withTime)
 916                            .onChange(of: withTime) {
 917                                if withTime { date = QuestionField.timed(date) }
 918                                text = QuestionField.stamp(date, withTime: withTime)
 919                            }
 920                        if withTime { DatePicker("Time", selection: $date, displayedComponents: .hourAndMinute) }
 921                    }
 922                    if !prompt.choices.isEmpty {
 923                        let matching = prompt.choices.filter { lastPart.isEmpty || $0.localizedCaseInsensitiveContains(lastPart) }
 924                        Section("Choices") {
 925                            ForEach(matching.prefix(50), id: \.self) { choice in
 926                                Button(choice) { choose(choice) }
 927                            }
 928                        }
 929                    }
 930                }
 931            }
 932            .navigationTitle(prompt.message.trimmingCharacters(in: CharacterSet(charactersIn: ": ")))
 933            .navigationBarTitleDisplayMode(.inline)
 934            .toolbar {
 935                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { answer(nil) } }
 936                if prompt.fast == nil || prompt.fast?.multiple == true {
 937                    ToolbarItem(placement: .confirmationAction) {
 938                        Button("Done") { answer(prompt.fast == nil ? text : FastSelection.encode(keys)) }
 939                            .disabled(prompt.requireMatch && prompt.fast == nil && !prompt.choices.isEmpty && !prompt.choices.contains(text))
 940                    }
 941                }
 942            }
 943        }
 944        .onAppear {
 945            text = prompt.initial
 946            date = prompt.date?.defaultDate ?? Calendar.current.startOfDay(for: Date())
 947        }
 948    }
 949
 950    /// With a separator (tags), what's typed after the last one.
 951    private var lastPart: String {
 952        guard let separator = prompt.completionSeparator else { return text }
 953        return String(text.split(separator: separator, omittingEmptySubsequences: false).last ?? "")
 954    }
 955
 956    private func choose(_ choice: String) {
 957        guard let separator = prompt.completionSeparator else {
 958            text = choice
 959            if prompt.date == nil { answer(choice) }
 960            return
 961        }
 962        var parts = text.split(separator: separator, omittingEmptySubsequences: false).map(String.init)
 963        if parts.isEmpty { parts = [""] }
 964        parts[parts.count - 1] = choice
 965        text = parts.joined(separator: String(separator)) + String(separator)
 966    }
 967
 968    @ViewBuilder
 969    private func fastSection(_ fast: FastSelection) -> some View {
 970        let current = fast.multiple ? fast.tags(after: keys) ?? [] : []
 971        Section {
 972            ForEach(Array(fast.options.enumerated()), id: \.offset) { _, option in
 973                Button {
 974                    if fast.multiple { keys.append(.key(option.key)) } else { answer(String(option.key)) }
 975                } label: {
 976                    HStack {
 977                        Text(option.name).foregroundStyle(.primary)
 978                        Spacer()
 979                        if current.contains(option.name) { Image(systemName: "checkmark") }
 980                        Text(String(option.key)).font(.caption.monospaced()).foregroundStyle(.secondary)
 981                    }
 982                }
 983            }
 984            if !fast.multiple {
 985                Button("No keyword") { answer(" ") }
 986            }
 987        } footer: {
 988            if fast.multiple, !fast.inherited.isEmpty { Text("Inherited: :" + fast.inherited.joined(separator: ":") + ":") }
 989        }
 990    }
 991}
 992
 993/// `org-edit-special` and `org-table-edit-field`: the text edited apart, put back with Save.
 994/// A src block's code is highlighted as its language.
 995struct BlockEditSheet: View {
 996    let edit: BlockEdit
 997    let theme: MobileTheme
 998    let finish: (String?) -> Void
 999    @State private var text: String?
1000
1001    var body: some View {
1002        NavigationStack {
1003            Group {
1004                if let text {
1005                    CodeTextView(text: text, language: edit.language, theme: theme) { self.text = $0 }
1006                }
1007            }
1008            .padding(.horizontal, 8)
1009            .navigationTitle(edit.title.replacingOccurrences(of: "Editing ", with: "").capitalized(with: nil))
1010            .navigationBarTitleDisplayMode(.inline)
1011            .toolbar {
1012                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { finish(nil) } }
1013                ToolbarItem(placement: .confirmationAction) { Button("Save") { finish(text ?? edit.content) } }
1014            }
1015        }
1016        .onAppear { text = edit.content }
1017    }
1018}
1019
1020/// A text view for code, restyled with the editor's highlighter after each change.
1021struct CodeTextView: UIViewRepresentable {
1022    let text: String
1023    let language: String?
1024    let theme: MobileTheme
1025    let changed: (String) -> Void
1026
1027    func makeUIView(context: Context) -> UITextView {
1028        let view = UITextView()
1029        view.autocorrectionType = .no
1030        view.autocapitalizationType = .none
1031        view.smartQuotesType = .no
1032        view.smartDashesType = .no
1033        view.spellCheckingType = .no
1034        view.keyboardDismissMode = .interactive
1035        view.backgroundColor = .clear
1036        view.text = text
1037        view.delegate = context.coordinator
1038        context.coordinator.style(view)
1039        DispatchQueue.main.async { view.becomeFirstResponder() }
1040        return view
1041    }
1042
1043    func updateUIView(_ view: UITextView, context: Context) {
1044        context.coordinator.parent = self
1045    }
1046
1047    func makeCoordinator() -> Coordinator { Coordinator(self) }
1048
1049    @MainActor
1050    final class Coordinator: NSObject, UITextViewDelegate {
1051        var parent: CodeTextView
1052        init(_ parent: CodeTextView) { self.parent = parent }
1053
1054        func textViewDidChange(_ view: UITextView) {
1055            parent.changed(view.text)
1056            style(view)
1057        }
1058
1059        /// The theme's font and color, then the language's token colors.
1060        func style(_ view: UITextView) {
1061            let storage = view.textStorage
1062            let whole = NSRange(location: 0, length: storage.length)
1063            let base: [NSAttributedString.Key: Any] = [.font: parent.theme.font, .foregroundColor: parent.theme.foreground]
1064            storage.beginEditing()
1065            storage.setAttributes(base, range: whole)
1066            if let language = parent.language {
1067                for run in MobileEditor.highlighter.highlights(language: language, code: storage.string) {
1068                    guard let key = run.category.themeKey, let color = parent.theme.color(key), run.range.upperBound <= storage.length else { continue }
1069                    storage.addAttribute(.foregroundColor, value: color, range: NSRange(location: run.range.lowerBound, length: run.range.count))
1070                }
1071            }
1072            storage.endEditing()
1073            view.typingAttributes = base
1074        }
1075    }
1076}
1077
1078/// Every command that applies at the caret, by name.
1079struct CommandPalette: View {
1080    let editor: MobileEditor
1081    /// The pane commands are offered (on iPad), and those for more than one pane.
1082    var panes = false
1083    var split = false
1084    /// Called with the chosen command before the palette closes.
1085    let choose: (String) -> Void
1086    @State private var query = ""
1087    @Environment(\.dismiss) private var dismiss
1088
1089    private static let viewCommands: [(id: String, title: String)] = [
1090        ("org.cycle", "Cycle Visibility"), ("org.cycle-global", "Cycle Global Visibility"),
1091        ("edit.undo", "Undo"), ("edit.redo", "Redo"),
1092        ("app.clock.in", "Clock In"), ("app.clock.out", "Clock Out"), ("app.clock.cancel", "Cancel Clock"),
1093        ("app.clock.goto", "Go to Clocked Entry"), ("app.clock.in-recent", "Clock In to Recent Entry…"),
1094        ("app.clock.in-last", "Clock In to Last Entry"), ("app.clock.goto-recent", "Go to Recent Clocked Entry…"),
1095        ("app.clock.default", "Mark as Default Clock Task"), ("app.clock.resolve", "Resolve Open Clocks…"),
1096        ("app.refile", "Refile…"), ("app.refile.copy", "Copy to Refile Target…"), ("app.refile.goto", "Go to Refile Target…"),
1097        ("app.archive", "Archive Subtree"), ("app.copy-rich-text", "Copy as Rich Text"), ("app.export.html-open", "Export to HTML and Open"),
1098        ("app.export-body-only", "Turn Body-Only Export On or Off"),
1099        ("app.export.icalendar-agenda", "Export Agenda Files to iCalendar"), ("app.export.icalendar-combined", "Combine Agenda Files into iCalendar"),
1100        ("app.publish", "Publish Project…"), ("app.publish.all", "Publish All Projects"), ("app.publish.current-file", "Publish Current File"),
1101        ("app.publish.current-project", "Publish Current Project"),
1102        ("app.toggle-markup", "Show or Hide Markup"),
1103        ("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"),
1104        ("edit.isearch-forward", "Incremental Search"), ("edit.isearch-backward", "Incremental Search Backward"),
1105        ("org.table.toggle-column-width", "Shrink or Expand Table Column"), ("org.table.shrink", "Shrink Table Columns with Widths"),
1106        ("org.table.expand", "Expand Table Columns"),
1107        ("app.table-import", "Import Table from File…"), ("app.table-export", "Export Table to File…"), ("app.plot", "Plot Table"),
1108        ("app.crypt.encrypt-entry", "Encrypt Entry…"), ("app.crypt.open-entry", "Decrypt Entry…"), ("app.crypt.decrypt-entry", "Decrypt Entry in File…"),
1109        ("app.crypt.encrypt-entries", "Encrypt Tagged Entries…"), ("app.crypt.forget-passphrase", "Forget Encryption Passphrase"),
1110        ("app.backlinks", "Show Backlinks"), ("app.node.find", "Find Node…"), ("app.node.insert", "Insert Node Link…"), ("app.node.graph", "Show Node Graph"),
1111        ("app.node.rename-from-front-matter", "Rename Note from Front Matter"),
1112        ("app.node.rename", "Rename Note…"),
1113        ("app.node.rename-folder-from-front-matter", "Rename Notes in Folder from Front Matter…"),
1114        ("app.node.silo-find", "Find Note in Silo…"),
1115        ("app.node.silo-create", "New Note in Silo…"),
1116        ("app.node.sequence-new-parent", "New Sequence Note…"),
1117        ("app.node.sequence-new-child", "New Child Sequence Note…"),
1118        ("app.node.sequence-new-sibling", "New Sibling Sequence Note…"),
1119        ("app.node.sequence-new-child-of-current", "New Child of This Note…"),
1120        ("app.node.sequence-new-sibling-of-current", "New Sibling of This Note…"),
1121        ("app.node.sequence-find", "Find Sequence Relatives…"),
1122        ("app.node.sequence-next-sibling", "Next Sibling Note"),
1123        ("app.node.sequence-previous-sibling", "Previous Sibling Note"),
1124        ("app.node.sequence-reparent", "Reparent Note…"),
1125        ("app.node.sequence-reparent-recursive", "Reparent Note with Descendants…"),
1126        ("app.node.sequence-rename-as-parent", "Rename Note as Sequence Parent"),
1127        ("app.node.sequence-convert", "Convert Note Sequence Scheme"),
1128        ("app.node.sequence-link", "Insert Sequence Link…"),
1129        ("app.node.sequence-hierarchy", "Sequence Hierarchy…"),
1130        ("app.dailies.today", "Go to Today's Daily Note"), ("app.dailies.yesterday", "Go to Yesterday's Daily Note"),
1131        ("app.dailies.tomorrow", "Go to Tomorrow's Daily Note"), ("app.dailies.date", "Go to Daily Note for Date…"),
1132        ("app.dailies.capture-today", "Capture to Today's Daily Note"), ("app.dailies.capture-yesterday", "Capture to Yesterday's Daily Note"),
1133        ("app.dailies.capture-tomorrow", "Capture to Tomorrow's Daily Note"), ("app.dailies.capture-date", "Capture to Daily Note for Date…"),
1134        ("app.dailies.next", "Next Daily Note"), ("app.dailies.previous", "Previous Daily Note"),
1135        ("app.attach.attach", "Attach File…"), ("app.attach.url", "Attach File from URL…"), ("app.attach.new", "New Attachment…"),
1136        ("app.attach.open", "Open Attachment…"), ("app.attach.reveal", "Show Attachment Folder"), ("app.attach.delete", "Delete Attachment…"),
1137        ("app.attach.delete-all", "Delete All Attachments…"), ("app.attach.sync", "Sync Attachments"),
1138        ("app.attach.set-directory", "Set Attachment Folder…"), ("app.attach.unset-directory", "Unset Attachment Folder"),
1139    ]
1140
1141    /// The commands that apply at the caret and their keys, worked out once when the palette
1142    /// opens rather than on every keystroke in the search field.
1143    @State private var applicable: [(id: String, title: String, keys: String?)]?
1144
1145    var body: some View {
1146        let shown = (applicable ?? []).filter { query.isEmpty || $0.title.localizedCaseInsensitiveContains(query) }
1147        NavigationStack {
1148            List(shown, id: \.id) { command in
1149                Button {
1150                    choose(command.id)
1151                    dismiss()
1152                } label: {
1153                    HStack {
1154                        Text(command.title).foregroundStyle(.primary)
1155                        Spacer()
1156                        if let keys = command.keys {
1157                            Text(keys).font(.caption.monospaced()).foregroundStyle(.secondary)
1158                        }
1159                    }
1160                }
1161            }
1162            .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always))
1163            .navigationTitle("Commands")
1164            .navigationBarTitleDisplayMode(.inline)
1165            .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Close") { dismiss() } } }
1166        }
1167        .onAppear {
1168            guard applicable == nil else { return }
1169            let context = editor.editContext()
1170            let paneCommands: [(id: String, title: String)] = !panes ? [] : [("app.split-right", "Split Pane Right"), ("app.split-below", "Split Pane Below")]
1171                + (split ? [("app.pane-next", "Next Pane"), ("app.pane-close", "Close Pane"), ("app.pane-only", "Close Other Panes")] : [])
1172            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) })
1173                .filter { editor.applies($0.id, in: context) }
1174                .map { ($0.id, CommandTitle.localized($0.title), editor.keymap.keyLabels(for: $0.id).first) }
1175        }
1176    }
1177}
1178/// A table as CSV or TSV, for the save dialog.
1179struct TableFile: FileDocument {
1180    static var readableContentTypes: [UTType] { [.commaSeparatedText, .tabSeparatedText] }
1181    let text: String
1182    let type: UTType
1183
1184    init(text: String, type: UTType) {
1185        self.text = text
1186        self.type = type
1187    }
1188
1189    init(configuration: ReadConfiguration) throws {
1190        text = configuration.file.regularFileContents.map { String(decoding: $0, as: UTF8.self) } ?? ""
1191        type = configuration.contentType
1192    }
1193
1194    func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
1195        FileWrapper(regularFileWithContents: Data(text.utf8))
1196    }
1197}
1198/// A plotted table, as the Mac's plot sheet shows it.
1199struct PlotScreen: View {
1200    let plot: TablePlot.Plot
1201    @Environment(\.dismiss) private var dismiss
1202
1203    var body: some View {
1204        NavigationStack {
1205            PlotChart(plot)
1206                .navigationTitle("Plot")
1207                .navigationBarTitleDisplayMode(.inline)
1208                .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } }
1209        }
1210    }
1211}
1212/// A file from the photo picker, copied out of the picker's temporary place with its name.
1213struct PickedFile: Transferable {
1214    let url: URL
1215
1216    static var transferRepresentation: some TransferRepresentation {
1217        FileRepresentation(importedContentType: .item) { received in
1218            let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
1219            try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
1220            let url = folder.appendingPathComponent(received.file.lastPathComponent)
1221            try FileManager.default.copyItem(at: received.file, to: url)
1222            return PickedFile(url: url)
1223        }
1224    }
1225}
1226
1227/// The passphrase sheet for org-crypt, its new text applied in the editor.
1228struct CryptScreen: View {
1229    let request: CryptRequest
1230    let session: DocumentSession
1231    let editor: MobileEditor?
1232    let report: (String) -> Void
1233    @Environment(\.dismiss) private var dismiss
1234
1235    var body: some View {
1236        NavigationStack {
1237            CryptSheet(request: request, text: { session.document?.text ?? "" }, apply: apply) { message in
1238                dismiss()
1239                if let message { report(message) }
1240            }
1241            .navigationBarTitleDisplayMode(.inline)
1242        }
1243    }
1244
1245    private func apply(_ new: String) {
1246        guard let editor else { return }
1247        let context = editor.editContext()
1248        let caret = min(context.caret, (new as NSString).length)
1249        _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
1250    }
1251}
1252/// The pane an editor screen made for itself, closed with the screen.
1253@MainActor
1254final class PaneHolder {
1255    var pane: EditorPane?
1256    nonisolated(unsafe) var release: (() -> Void)?
1257
1258    deinit {
1259        guard let release else { return }
1260        Task { @MainActor in release() }
1261    }
1262}
1263
1264/// The screen's title, unless a split shows the focused pane's.
1265private struct EditorTitle: ViewModifier {
1266    let title: String
1267    let shown: Bool
1268
1269    func body(content: Content) -> some View {
1270        if shown {
1271            content.navigationTitle(title).navigationBarTitleDisplayMode(.inline)
1272        } else {
1273            content
1274        }
1275    }
1276}
1277#endif