Sources/OrgstarMobile/EditorScreen.swift

1e2bc5fb0b3e80e3b2d877c37d07f3ec7f183be2
orgstar/Sources/OrgstarMobile/EditorScreen.swift

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