Sources/OrgstarMobile/EditorScreen.swift

a15753a827b5ab7a0ccf3a0873890771c2979ee7
orgstar/Sources/OrgstarMobile/EditorScreen.swift

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