Sources/OrgstarMobile/EditorScreen.swift

10c0d64a19b13f9e27044e7dd3edb2b708038aed
orgstar/Sources/OrgstarMobile/EditorScreen.swift

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