Sources/OrgstarMobile/EditorScreen.swift

2986af1074ecbcd8b4975e0e046c502117a6c4f9
orgstar/Sources/OrgstarMobile/EditorScreen.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form