Sources/OrgstarMobile/EditorScreen.swift

ea98aa303287e7bc94425330f51d3c2dfd1ef77e
orgstar/Sources/OrgstarMobile/EditorScreen.swift

756 lines · 35299 bytes

  1#if os(iOS)
  2import OrgApp
  3import OrgCore
  4import OrgDocument
  5import SwiftUI
  6import UIKit
  7import UniformTypeIdentifiers
  8
  9/// Editing a file: the text with Org's folding and styling, a bar of Org keys over the keyboard,
 10/// and every command in a palette. The editor is the open file's live state, so autosave and
 11/// merging go through the session as on the Mac.
 12struct EditorScreen: View {
 13    let path: String
 14    let offset: Int?
 15    let workspace: WorkspaceModel
 16    let session: DocumentSession
 17    @State private var editor: MobileEditor?
 18    @State private var prompt: PromptRequest?
 19    @State private var message: String?
 20    @State private var sheet: Sheet?
 21    @State private var trust = TrustStore()
 22    /// The command chosen in the palette, run once the palette is gone.
 23    @State private var chosen: String?
 24    @Environment(ClockModel.self) private var clock
 25    @Environment(MobileModel.self) private var model
 26    @Environment(\.openURL) private var openURL
 27
 28    /// The session's options with `buffer-file-name` and the agenda files, for clock tables.
 29    private var editorOptions: EditingOptions {
 30        var options = session.options
 31        options.filePath = path
 32        options.agendaFiles = workspace.agendaFilePaths()
 33        return options
 34    }
 35
 36    struct PromptRequest: Identifiable {
 37        let id = UUID()
 38        let prompt: Prompt
 39        let reply: (String?) -> Void
 40    }
 41
 42    /// One sheet at a time: two presenters on this screen interfere.
 43    /// `org-table-import`'s file picker is up.
 44    @State private var importingTable = false
 45    /// The table at the caret, for `org-table-export`'s save dialog.
 46    @State private var exportedTable: TableFile?
 47
 48    enum Sheet: Identifiable {
 49        case palette, conflict, syncCopies, recovery
 50        /// `app.refile`, `app.refile.copy` or `app.refile.goto`.
 51        case refile(String)
 52        case block(BlockEdit)
 53        case columns(ColumnView.View)
 54        case plot(TablePlot.Plot)
 55        case crypt(CryptRequest)
 56
 57        var id: String {
 58            switch self {
 59            case .palette: "palette"
 60            case .refile(let command): command
 61            case .conflict: "conflict"
 62            case .syncCopies: "syncCopies"
 63            case .recovery: "recovery"
 64            case .block(let edit): "block \(edit.range)"
 65            case .columns: "columns"
 66            case .plot: "plot"
 67            case .crypt(let request): request.id.uuidString
 68            }
 69        }
 70    }
 71
 72    var body: some View {
 73        Group {
 74            if let editor {
 75                EditorTextView(editor: editor, palette: { sheet = .palette })
 76                    .ignoresSafeArea(.container, edges: .bottom)
 77            } else {
 78                ProgressView()
 79            }
 80        }
 81        .navigationTitle(session.bufferName(path) + (session.dirtyPaths.contains(path) ? " •" : ""))
 82        .navigationBarTitleDisplayMode(.inline)
 83        .toolbar(.hidden, for: .tabBar)
 84        .toolbar {
 85            ToolbarItemGroup(placement: .primaryAction) {
 86                if session.conflict != nil {
 87                    Button("Conflict", systemImage: "exclamationmark.triangle") { sheet = .conflict }
 88                }
 89                Button("Undo", systemImage: "arrow.uturn.backward") { editor?.run("edit.undo") }
 90                Menu("More", systemImage: "ellipsis.circle") {
 91                    Button("Commands", systemImage: "command") { sheet = .palette }
 92                    Button("Clock In", systemImage: "stopwatch") { editor?.run("app.clock.in") }
 93                    Button("Column View", systemImage: "tablecells") { editor?.run("org.columns") }
 94                    Button("Column View of File", systemImage: "tablecells.badge.ellipsis") { editor?.run("org.columns.global") }
 95                    Menu("Table", systemImage: "tablecells") {
 96                        Button("Import Table from File…", systemImage: "square.and.arrow.down") { importingTable = true }
 97                        Button("Export Table as CSV…", systemImage: "square.and.arrow.up") { exportTable(csv: true) }
 98                        Button("Export Table as TSV…", systemImage: "square.and.arrow.up") { exportTable(csv: false) }
 99                        Button("Plot Table", systemImage: "chart.xyaxis.line") { plotTable() }
100                    }
101                    Toggle(isOn: Binding(get: { model.showMarkup }, set: { model.showMarkup = $0 })) {
102                        Label("Show Markup", systemImage: "chevron.left.forwardslash.chevron.right")
103                    }
104                    RecentClockMenu(clock: clock) { editor?.run($0) }
105                    Menu("Encryption", systemImage: "lock") {
106                        Button("Encrypt Entry…", systemImage: "lock") { crypt("app.crypt.encrypt-entry") }
107                        Button("Decrypt Entry…", systemImage: "lock.open") { crypt("app.crypt.open-entry") }
108                        Button("Decrypt Entry in File…", systemImage: "lock.open.trianglebadge.exclamationmark") { crypt("app.crypt.decrypt-entry") }
109                        Button("Encrypt Tagged Entries…", systemImage: "lock.rectangle.stack") { crypt("app.crypt.encrypt-entries") }
110                        Button("Forget Encryption Passphrase", systemImage: "key.slash") { crypt("app.crypt.forget-passphrase") }
111                    }
112                    if let text = session.document?.text, session.path == path { ExportMenu(path: path, text: text) { message = $0 } }
113                    Button("Sync Conflict Copies", systemImage: "doc.on.doc") { sheet = .syncCopies }
114                    Button("Recovered Versions", systemImage: "clock.arrow.circlepath") { sheet = .recovery }
115                }
116            }
117        }
118        .safeAreaInset(edge: .top) {
119            if let message {
120                Text(message).font(.callout).padding(8).frame(maxWidth: .infinity).background(.bar)
121                    .onTapGesture { self.message = nil }
122                    .task(id: message) {
123                        try? await Task.sleep(for: .seconds(4))
124                        if self.message == message { self.message = nil }
125                    }
126            }
127        }
128        .sheet(item: $prompt) { request in
129            PromptSheet(prompt: request.prompt) { answer in
130                prompt = nil
131                request.reply(answer)
132            }
133        }
134        .sheet(item: $sheet, onDismiss: {
135            // After the sheet has gone, so a command's own prompt can show.
136            if let id = chosen {
137                chosen = nil
138                editor?.run(id)
139            }
140        }) { sheet in
141            switch sheet {
142            case .palette: if let editor { CommandPalette(editor: editor) { chosen = $0 } }
143            case .conflict: ConflictSheet(session: session)
144            case .syncCopies: SyncConflictSheet(session: session) { message = $0 }
145            case .recovery: RecoverySheet(session: session) { message = $0 }
146            case .refile(let command):
147                RefileSheet(targets: workspace.refileTargets(openPath: session.path, document: session.document),
148                            create: command == "app.refile.goto" || OrgPreferences.refileSettings().creating == .no ? nil : { parent, child in
149                    self.sheet = nil
150                    switch session.createRefileChild(under: parent, title: child) {
151                    case .success(let target):
152                        guard let path = session.path, let editor else { return }
153                        message = session.refile(to: target, from: (path, editor.editContext().caret), keep: command == "app.refile.copy")
154                    case .failure(.message(let text)): message = text
155                    }
156                }) { target in
157                    self.sheet = nil
158                    guard let target else { return }
159                    if command == "app.refile.goto" {
160                        model.openRequest = .offset(target.path, target.start ?? Int.max)
161                    } else {
162                        refile(to: target, keep: command == "app.refile.copy")
163                    }
164                }
165            case .block(let edit):
166                BlockEditSheet(edit: edit, theme: MobileTheme(model.theme)) { content in
167                    self.sheet = nil
168                    if let content, let editor { _ = editor.perform(ReplaceBlockLines(edit: edit, content: content)) }
169                }
170            case .columns(let view):
171                ColumnViewScreen(view: view, session: session, path: path) { offset in editor?.reveal(offset) }
172            case .plot(let plot):
173                PlotScreen(plot: plot)
174            case .crypt(let request):
175                CryptScreen(request: request, session: session, editor: editor) { message = $0 }
176            }
177        }
178        .fileImporter(isPresented: $importingTable, allowedContentTypes: [.commaSeparatedText, .tabSeparatedText, .plainText]) { result in
179            importTable(result)
180        }
181        .fileExporter(isPresented: Binding(get: { exportedTable != nil }, set: { if !$0 { exportedTable = nil } }),
182                      document: exportedTable, contentType: exportedTable?.type ?? .commaSeparatedText,
183                      defaultFilename: exportedTable?.type == .tabSeparatedText ? "table.tsv" : "table.csv") { result in
184            if case .failure(let error) = result { message = error.localizedDescription } else { message = "Export done." }
185        }
186        .onChange(of: session.conflict) { _, conflict in
187            if conflict != nil, session.path == path { sheet = .conflict }
188        }
189        .onChange(of: session.lastError) { _, error in
190            if let error { message = error; session.lastError = nil }
191        }
192        .onAppear(perform: start)
193        .onChange(of: session.revealRequest?.id) {
194            if let offset = session.revealRequest?.offset, session.path == path { editor?.reveal(offset) }
195        }
196        .onChange(of: model.settingsVersion) {
197            editor?.options = editorOptions
198            editor?.themeSpec = model.theme
199            editor?.keymap = model.keymap
200            editor?.modal = model.modalKeys
201        }
202        .onChange(of: model.showMarkup) { editor?.showMarkup = model.showMarkup }
203        .onDisappear {
204            // Typing the reader shows next, and a save, don't wait for the autosave delay.
205            if session.dirtyPaths.contains(path) { _ = session.save(path) }
206        }
207    }
208
209    /// Store Link, Store ID Link and Insert Link, with the links stored while the app runs.
210    private func link(_ id: String) {
211        guard let editor else { return }
212        switch id {
213        case "org.link.store":
214            message = StoredLink.add(Links.store(in: editor.editContext(), path: Links.abbreviate(path, home: NSHomeDirectory())), to: &model.storedLinks)
215        case "org.id.store-link":
216            if case .commit = editor.perform(CreateID()),
217               let link = Links.storeID(in: editor.editContext(), fileName: (path as NSString).lastPathComponent) {
218                message = StoredLink.add(link, to: &model.storedLinks)
219            }
220        default:
221            _ = editor.perform(InsertLink(stored: model.storedLinks, file: path))
222        }
223    }
224
225    /// Runs a block once it's trusted, asking as `org-confirm-babel-evaluate` does.
226    private func run(_ job: BabelJob) {
227        let go = {
228            message = "Running \(job.language) block…"
229            session.startBabel(job) { message = $0 }
230        }
231        if !job.alwaysAsk, trust.isTrusted(path: path, content: job.blockText) { return go() }
232        let choices = job.alwaysAsk ? ["yes", "no"] : ["yes", "no", "always"]
233        prompt = PromptRequest(prompt: Prompt(key: "confirm", message: "Run this \(job.language) block?", choices: choices)) { answer in
234            switch answer {
235            case "always":
236                trust.trust(path: path, content: job.blockText)
237                go()
238            case "yes": go()
239            default: message = "Not run"
240            }
241        }
242    }
243
244    private func start() {
245        if session.path != path { session.open(path) }
246        if editor == nil, let document = session.document {
247            let editor = MobileEditor(
248                document: document, editable: document.isEditable, options: editorOptions, theme: model.theme,
249                showMarkup: model.showMarkup, baseDirectory: URL(fileURLWithPath: path).deletingLastPathComponent()
250            )
251            editor.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] }
252            editor.onChange = { [weak session] in session?.bufferChanged(path) }
253            editor.onMessage = { message = $0 }
254            editor.onPrompt = { prompt, reply in self.prompt = PromptRequest(prompt: prompt, reply: reply) }
255            editor.onLink = { link in
256                switch session.follow(link, workspace: workspace, isText: { _ in false }) {
257                case .shown: message = session.path == path ? nil : "Opened \((session.path.map { ($0 as NSString).lastPathComponent }) ?? "")"
258                case .openExternally(let url): openURL(url)
259                case .message(let text): message = text
260                }
261            }
262            editor.onEditBlock = { edit in sheet = .block(edit) }
263            editor.onColumnView = { view in sheet = .columns(view) }
264            editor.onTangle = { scope in message = session.tangle(scope) }
265            editor.onBabel = { job in run(job) }
266            editor.onRefreshSetup = { session.refreshSetup() }
267            editor.onAgenda = { start, count in model.agendaRequest = .init(start: start, count: count) }
268            editor.keymap = model.keymap
269            editor.modal = model.modalKeys
270            editor.onAppCommand = { id in
271                if id == "app.save" {
272                    _ = session.save(path)
273                } else if ["app.refile", "app.refile.copy", "app.refile.goto"].contains(id) {
274                    sheet = .refile(id)
275                } else if id == "app.table-import" {
276                    importingTable = true
277                } else if id == "app.table-export" {
278                    exportTable(csv: true)
279                } else if id == "app.plot" {
280                    plotTable()
281                } else if id.hasPrefix("app.crypt.") {
282                    crypt(id)
283                } else if id == "app.toggle-markup" {
284                    model.showMarkup.toggle()
285                } else if MobileEditor.linkCommands.contains(id) {
286                    link(id)
287                } else if !MobileClock.run(id, model: model, workspace: workspace, show: { message = $0 }) {
288                    message = "Not available on iOS yet"
289                }
290            }
291            self.editor = editor
292        }
293        if let editor { session.attach(editor) }
294        if let offset { editor?.reveal(offset) }
295        if session.conflict != nil {
296            sheet = .conflict
297        } else if case let copies = session.syncConflictCopies().count, copies > 0 {
298            message = "\(copies) sync conflict \(copies == 1 ? "copy" : "copies") of this file; More › Sync Conflict Copies compares them."
299        }
300    }
301}
302
303extension EditorScreen {
304    /// `org-table-import`: a TSV, CSV or space-separated file becomes a table at the caret.
305    private func importTable(_ result: Result<URL, Error>) {
306        guard case .success(let url) = result, let editor else { return }
307        let scoped = url.startAccessingSecurityScopedResource()
308        defer { if scoped { url.stopAccessingSecurityScopedResource() } }
309        guard let contents = try? String(contentsOf: url, encoding: .utf8) else { return message = "Can't read \(url.lastPathComponent)" }
310        _ = editor.perform(ImportTable(contents: contents))
311    }
312
313    /// org-crypt's commands at the caret, through the passphrase sheet.
314    private func crypt(_ id: String) {
315        guard let editor else { return }
316        let context = editor.editContext()
317        switch id {
318        case "app.crypt.forget-passphrase":
319            CryptPassphrases.forget(path)
320            message = "Passphrase forgotten for \((path as NSString).lastPathComponent)"
321        case "app.crypt.encrypt-entries":
322            sheet = .crypt(CryptRequest(mode: .encryptAll(tag: OrgPreferences.cryptTag()), path: path, offset: context.caret))
323        default:
324            guard OrgCrypt.heading(context.text, at: context.caret) != nil else { return message = "Before first headline" }
325            let encrypted = OrgCrypt.encryptedRange(context.text, at: context.caret) != nil
326            if id == "app.crypt.encrypt-entry" {
327                guard !encrypted else { return message = "The entry is encrypted already" }
328                sheet = .crypt(CryptRequest(mode: .encrypt, path: path, offset: context.caret))
329            } else {
330                guard encrypted else { return message = "Not an encrypted entry" }
331                sheet = .crypt(CryptRequest(mode: id == "app.crypt.open-entry" ? .open : .decryptInPlace, path: path, offset: context.caret))
332            }
333        }
334    }
335
336    /// `org-plot/gnuplot`, drawn by Swift Charts: written to `file:` when the options name
337    /// one, else shown.
338    private func plotTable() {
339        guard let editor else { return }
340        let context = editor.editContext()
341        do {
342            let plot = try TablePlot.plot(context.text, at: context.caret)
343            if let url = PlotOutput.file(plot, directory: URL(fileURLWithPath: path).deletingLastPathComponent()) {
344                try PlotOutput.write(plot, to: url)
345                message = "Plot written to \(url.lastPathComponent)"
346                if editor.showsImages { editor.restyleAll() }
347            } else {
348                sheet = .plot(plot)
349            }
350        } catch {
351            message = "\(error)"
352        }
353    }
354
355    /// `org-table-export` of the table at the caret, as CSV or TSV.
356    private func exportTable(csv: Bool) {
357        guard let editor else { return }
358        let context = editor.editContext()
359        guard let text = ImportTable.exportText(context.text, at: context.caret, path: csv ? "table.csv" : "table.tsv") else {
360            return message = "No table at point"
361        }
362        exportedTable = TableFile(text: text, type: csv ? .commaSeparatedText : .tabSeparatedText)
363    }
364
365    /// `org-refile` of the entry at the caret, to a target worked out again from the files
366    /// now, as the agenda's Refile… does.
367    func refile(to target: RefileTarget, keep: Bool = false) {
368        guard let editor, let path = session.path else { return }
369        let caret = editor.editContext().caret
370        guard let current = workspace.refileTargets(openPath: path, document: session.document).first(where: { $0.label == target.label }) else {
371            message = "Can't find \(target.label) any more."
372            return
373        }
374        message = session.refile(to: current, from: (path, caret), keep: keep)
375    }
376}
377
378/// The editor's text view, with the Org key bar over the keyboard.
379struct EditorTextView: UIViewRepresentable {
380    let editor: MobileEditor
381    let palette: () -> Void
382
383    func makeUIView(context: Context) -> UITextView {
384        let bar = UIHostingController(rootView: KeyBar(editor: editor, palette: palette))
385        bar.view.frame = CGRect(x: 0, y: 0, width: 400, height: 48)
386        bar.view.backgroundColor = .clear
387        bar.sizingOptions = []
388        editor.textView.inputAccessoryView = bar.view
389        context.coordinator.bar = bar
390        return editor.textView
391    }
392
393    func updateUIView(_ view: UITextView, context: Context) {}
394
395    func makeCoordinator() -> Coordinator { Coordinator() }
396
397    final class Coordinator {
398        var bar: UIViewController?
399    }
400}
401
402/// Org's keys for a touch keyboard: each button does what its key does at the caret, as the
403/// Emacs keymap binds it (M-→ demotes a heading, indents an item, moves a table column).
404struct KeyBar: View {
405    let editor: MobileEditor
406    let palette: () -> Void
407
408    private static let keys: [(label: String, symbol: String?, keys: String)] = [
409        ("Fold", "arrow.right.to.line", "TAB"),
410        ("Overview", "arrow.left.to.line", "S-TAB"),
411        ("Promote", "arrow.left", "M-<left>"),
412        ("Demote", "arrow.right", "M-<right>"),
413        ("Move up", "arrow.up", "M-<up>"),
414        ("Move down", "arrow.down", "M-<down>"),
415        ("New heading or item", "plus", "M-RET"),
416        ("TODO", nil, "C-c C-t"),
417        ("Act at point", "checkmark.square", "C-c C-c"),
418        ("Schedule", "calendar", "C-c C-s"),
419        ("Deadline", "calendar.badge.exclamationmark", "C-c C-d"),
420        ("Tags", "tag", "C-c C-q"),
421        ("Open link", "link", "C-c C-o"),
422    ]
423
424    var body: some View {
425        ScrollView(.horizontal, showsIndicators: false) {
426            HStack(spacing: 4) {
427                Button("Commands", systemImage: "command", action: palette)
428                ForEach(Self.keys, id: \.keys) { key in
429                    Button {
430                        editor.run(keys: key.keys)
431                    } label: {
432                        if let symbol = key.symbol { Label(key.label, systemImage: symbol) } else { Text(key.label).font(.callout.weight(.semibold)) }
433                    }
434                    .accessibilityLabel(key.label)
435                }
436                Button("Hide keyboard", systemImage: "keyboard.chevron.compact.down") { editor.textView.resignFirstResponder() }
437            }
438            .labelStyle(.iconOnly)
439            .buttonStyle(.bordered)
440            .padding(.horizontal, 8)
441            .padding(.vertical, 6)
442        }
443        .background(.bar)
444    }
445}
446
447/// A command's question: text with choices, a date, or fast selection by keys.
448struct PromptSheet: View {
449    let prompt: Prompt
450    let answer: (String?) -> Void
451    @State private var text = ""
452    @State private var date = Date()
453    @State private var keys: [FastSelection.Input] = []
454
455    var body: some View {
456        NavigationStack {
457            Form {
458                if let fast = prompt.fast {
459                    fastSection(fast)
460                } else {
461                    Section {
462                        TextField(prompt.message, text: $text)
463                            .autocorrectionDisabled()
464                            .textInputAutocapitalization(.never)
465                            .onSubmit { answer(text) }
466                    } footer: {
467                        if prompt.date != nil { Text("Org's date syntax works too: +2d, fri, 14:00") }
468                    }
469                    if prompt.date != nil {
470                        DatePicker("Date", selection: $date, displayedComponents: [.date])
471                            .datePickerStyle(.graphical)
472                            .onChange(of: date) { text = Self.stamp(date) }
473                    }
474                    if !prompt.choices.isEmpty {
475                        let matching = prompt.choices.filter { lastPart.isEmpty || $0.localizedCaseInsensitiveContains(lastPart) }
476                        Section("Choices") {
477                            ForEach(matching.prefix(50), id: \.self) { choice in
478                                Button(choice) { choose(choice) }
479                            }
480                        }
481                    }
482                }
483            }
484            .navigationTitle(prompt.message.trimmingCharacters(in: CharacterSet(charactersIn: ": ")))
485            .navigationBarTitleDisplayMode(.inline)
486            .toolbar {
487                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { answer(nil) } }
488                if prompt.fast == nil || prompt.fast?.multiple == true {
489                    ToolbarItem(placement: .confirmationAction) {
490                        Button("Done") { answer(prompt.fast == nil ? text : FastSelection.encode(keys)) }
491                            .disabled(prompt.requireMatch && prompt.fast == nil && !prompt.choices.isEmpty && !prompt.choices.contains(text))
492                    }
493                }
494            }
495        }
496        .onAppear {
497            text = prompt.initial
498            if let day = prompt.date?.defaultDate { date = day }
499        }
500    }
501
502    /// With a separator (tags), what's typed after the last one.
503    private var lastPart: String {
504        guard let separator = prompt.completionSeparator else { return text }
505        return String(text.split(separator: separator, omittingEmptySubsequences: false).last ?? "")
506    }
507
508    private func choose(_ choice: String) {
509        guard let separator = prompt.completionSeparator else {
510            text = choice
511            if prompt.date == nil { answer(choice) }
512            return
513        }
514        var parts = text.split(separator: separator, omittingEmptySubsequences: false).map(String.init)
515        if parts.isEmpty { parts = [""] }
516        parts[parts.count - 1] = choice
517        text = parts.joined(separator: String(separator)) + String(separator)
518    }
519
520    @ViewBuilder
521    private func fastSection(_ fast: FastSelection) -> some View {
522        let current = fast.multiple ? fast.tags(after: keys) ?? [] : []
523        Section {
524            ForEach(Array(fast.options.enumerated()), id: \.offset) { _, option in
525                Button {
526                    if fast.multiple { keys.append(.key(option.key)) } else { answer(String(option.key)) }
527                } label: {
528                    HStack {
529                        Text(option.name).foregroundStyle(.primary)
530                        Spacer()
531                        if current.contains(option.name) { Image(systemName: "checkmark") }
532                        Text(String(option.key)).font(.caption.monospaced()).foregroundStyle(.secondary)
533                    }
534                }
535            }
536            if !fast.multiple {
537                Button("No keyword") { answer(" ") }
538            }
539        } footer: {
540            if fast.multiple, !fast.inherited.isEmpty { Text("Inherited: :" + fast.inherited.joined(separator: ":") + ":") }
541        }
542    }
543
544    static func stamp(_ date: Date) -> String {
545        let formatter = DateFormatter()
546        formatter.locale = Locale(identifier: "en_US_POSIX")
547        formatter.dateFormat = "yyyy-MM-dd"
548        return formatter.string(from: date)
549    }
550}
551
552/// `org-edit-special` and `org-table-edit-field`: the text edited apart, put back with Save.
553/// A src block's code is highlighted as its language.
554struct BlockEditSheet: View {
555    let edit: BlockEdit
556    let theme: MobileTheme
557    let finish: (String?) -> Void
558    @State private var text: String?
559
560    var body: some View {
561        NavigationStack {
562            Group {
563                if let text {
564                    CodeTextView(text: text, language: edit.language, theme: theme) { self.text = $0 }
565                }
566            }
567            .padding(.horizontal, 8)
568            .navigationTitle(edit.title.replacingOccurrences(of: "Editing ", with: "").capitalized(with: nil))
569            .navigationBarTitleDisplayMode(.inline)
570            .toolbar {
571                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { finish(nil) } }
572                ToolbarItem(placement: .confirmationAction) { Button("Save") { finish(text ?? edit.content) } }
573            }
574        }
575        .onAppear { text = edit.content }
576    }
577}
578
579/// A text view for code, restyled with the editor's highlighter after each change.
580struct CodeTextView: UIViewRepresentable {
581    let text: String
582    let language: String?
583    let theme: MobileTheme
584    let changed: (String) -> Void
585
586    func makeUIView(context: Context) -> UITextView {
587        let view = UITextView()
588        view.autocorrectionType = .no
589        view.autocapitalizationType = .none
590        view.smartQuotesType = .no
591        view.smartDashesType = .no
592        view.spellCheckingType = .no
593        view.keyboardDismissMode = .interactive
594        view.backgroundColor = .clear
595        view.text = text
596        view.delegate = context.coordinator
597        context.coordinator.style(view)
598        DispatchQueue.main.async { view.becomeFirstResponder() }
599        return view
600    }
601
602    func updateUIView(_ view: UITextView, context: Context) {
603        context.coordinator.parent = self
604    }
605
606    func makeCoordinator() -> Coordinator { Coordinator(self) }
607
608    @MainActor
609    final class Coordinator: NSObject, UITextViewDelegate {
610        var parent: CodeTextView
611        init(_ parent: CodeTextView) { self.parent = parent }
612
613        func textViewDidChange(_ view: UITextView) {
614            parent.changed(view.text)
615            style(view)
616        }
617
618        /// The theme's font and color, then the language's token colors.
619        func style(_ view: UITextView) {
620            let storage = view.textStorage
621            let whole = NSRange(location: 0, length: storage.length)
622            let base: [NSAttributedString.Key: Any] = [.font: parent.theme.font, .foregroundColor: parent.theme.foreground]
623            storage.beginEditing()
624            storage.setAttributes(base, range: whole)
625            if let language = parent.language {
626                for run in MobileEditor.highlighter.highlights(language: language, code: storage.string) {
627                    guard let key = run.category.themeKey, let color = parent.theme.color(key), run.range.upperBound <= storage.length else { continue }
628                    storage.addAttribute(.foregroundColor, value: color, range: NSRange(location: run.range.lowerBound, length: run.range.count))
629                }
630            }
631            storage.endEditing()
632            view.typingAttributes = base
633        }
634    }
635}
636
637/// Every command that applies at the caret, by name.
638struct CommandPalette: View {
639    let editor: MobileEditor
640    /// Called with the chosen command before the palette closes.
641    let choose: (String) -> Void
642    @State private var query = ""
643    @Environment(\.dismiss) private var dismiss
644
645    private static let viewCommands: [(id: String, title: String)] = [
646        ("org.cycle", "Cycle Visibility"), ("org.cycle-global", "Cycle Global Visibility"),
647        ("edit.undo", "Undo"), ("edit.redo", "Redo"),
648        ("app.clock.in", "Clock In"), ("app.clock.out", "Clock Out"), ("app.clock.cancel", "Cancel Clock"),
649        ("app.clock.goto", "Go to Clocked Entry"), ("app.clock.in-recent", "Clock In to Recent Entry…"),
650        ("app.clock.in-last", "Clock In to Last Entry"), ("app.clock.goto-recent", "Go to Recent Clocked Entry…"),
651        ("app.clock.default", "Mark as Default Clock Task"), ("app.clock.resolve", "Resolve Open Clocks…"),
652        ("app.refile", "Refile…"), ("app.refile.copy", "Copy to Refile Target…"), ("app.refile.goto", "Go to Refile Target…"),
653        ("app.toggle-markup", "Show or Hide Markup"),
654        ("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"),
655        ("org.table.toggle-column-width", "Shrink or Expand Table Column"), ("org.table.shrink", "Shrink Table Columns with Widths"),
656        ("org.table.expand", "Expand Table Columns"),
657        ("app.table-import", "Import Table from File…"), ("app.table-export", "Export Table to File…"), ("app.plot", "Plot Table"),
658        ("app.crypt.encrypt-entry", "Encrypt Entry…"), ("app.crypt.open-entry", "Decrypt Entry…"), ("app.crypt.decrypt-entry", "Decrypt Entry in File…"),
659        ("app.crypt.encrypt-entries", "Encrypt Tagged Entries…"), ("app.crypt.forget-passphrase", "Forget Encryption Passphrase"),
660    ]
661
662    /// The commands that apply at the caret and their keys, worked out once when the palette
663    /// opens rather than on every keystroke in the search field.
664    @State private var applicable: [(id: String, title: String, keys: String?)]?
665
666    var body: some View {
667        let shown = (applicable ?? []).filter { query.isEmpty || $0.title.localizedCaseInsensitiveContains(query) }
668        NavigationStack {
669            List(shown, id: \.id) { command in
670                Button {
671                    choose(command.id)
672                    dismiss()
673                } label: {
674                    HStack {
675                        Text(command.title).foregroundStyle(.primary)
676                        Spacer()
677                        if let keys = command.keys {
678                            Text(keys).font(.caption.monospaced()).foregroundStyle(.secondary)
679                        }
680                    }
681                }
682            }
683            .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always))
684            .navigationTitle("Commands")
685            .navigationBarTitleDisplayMode(.inline)
686            .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Close") { dismiss() } } }
687        }
688        .onAppear {
689            guard applicable == nil else { return }
690            let context = editor.editContext()
691            applicable = (Self.viewCommands + Commands.everything.map { ($0.id, $0.title) })
692                .filter { editor.applies($0.id, in: context) }
693                .map { ($0.id, $0.title, editor.keymap.keyLabels(for: $0.id).first) }
694        }
695    }
696}
697/// A table as CSV or TSV, for the save dialog.
698struct TableFile: FileDocument {
699    static var readableContentTypes: [UTType] { [.commaSeparatedText, .tabSeparatedText] }
700    let text: String
701    let type: UTType
702
703    init(text: String, type: UTType) {
704        self.text = text
705        self.type = type
706    }
707
708    init(configuration: ReadConfiguration) throws {
709        text = configuration.file.regularFileContents.map { String(decoding: $0, as: UTF8.self) } ?? ""
710        type = configuration.contentType
711    }
712
713    func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
714        FileWrapper(regularFileWithContents: Data(text.utf8))
715    }
716}
717/// A plotted table, as the Mac's plot sheet shows it.
718struct PlotScreen: View {
719    let plot: TablePlot.Plot
720    @Environment(\.dismiss) private var dismiss
721
722    var body: some View {
723        NavigationStack {
724            PlotChart(plot)
725                .navigationTitle("Plot")
726                .navigationBarTitleDisplayMode(.inline)
727                .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } }
728        }
729    }
730}
731/// The passphrase sheet for org-crypt, its new text applied in the editor.
732struct CryptScreen: View {
733    let request: CryptRequest
734    let session: DocumentSession
735    let editor: MobileEditor?
736    let report: (String) -> Void
737    @Environment(\.dismiss) private var dismiss
738
739    var body: some View {
740        NavigationStack {
741            CryptSheet(request: request, text: { session.document?.text ?? "" }, apply: apply) { message in
742                dismiss()
743                if let message { report(message) }
744            }
745            .navigationBarTitleDisplayMode(.inline)
746        }
747    }
748
749    private func apply(_ new: String) {
750        guard let editor else { return }
751        let context = editor.editContext()
752        let caret = min(context.caret, (new as NSString).length)
753        _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
754    }
755}
756#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