Sources/OrgstarMobile/EditorScreen.swift

586bad784d2cb2ad1bb43da0e63f0819913ed1dc
orgstar/Sources/OrgstarMobile/EditorScreen.swift

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