Sources/OrgstarMobile/EditorScreen.swift

30fb15c9bc849ec1e8371b73bd02d071a4b4eb2a
orgstar/Sources/OrgstarMobile/EditorScreen.swift

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