Sources/OrgstarMobile/EditorScreen.swift

754eac2f33eae31805a148fcf0bddeb74b95a4a3
orgstar/Sources/OrgstarMobile/EditorScreen.swift

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