Sources/OrgstarMobile/EditorScreen.swift

7e98a2ca205eea3866d838a6b794b9a2e5627cfd
orgstar/Sources/OrgstarMobile/EditorScreen.swift

1361 lines · 69572 bytes

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