Sources/OrgstarMobile/EditorScreen.swift

3aa264c947476955d58c5cccc70e97072bb47877
orgstar/Sources/OrgstarMobile/EditorScreen.swift

1285 lines · 65162 bytes

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