Sources/OrgstarMobile/EditorScreen.swift

9945f06859a5feee9b6af3496e944cb6b395715b
orgstar/Sources/OrgstarMobile/EditorScreen.swift

1332 lines · 67984 bytes

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