Sources/OrgstarMobile/EditorScreen.swift

071e94ac597ceadb3ee079a0401d882f11c45a76
orgstar/Sources/OrgstarMobile/EditorScreen.swift

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