Sources/OrgstarMobile/EditorScreen.swift

a79f5362fbc7c9473d040271cb3e718f88e5daf6
orgstar/Sources/OrgstarMobile/EditorScreen.swift

1303 lines · 66300 bytes

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