Sources/OrgstarMobile/MobileEditor.swift

7d77bed2106790e8555535f723f1411dd6d8e268
orgstar/Sources/OrgstarMobile/MobileEditor.swift

808 lines · 40691 bytes

  1#if os(iOS)
  2import OrgApp
  3import OrgCore
  4import OrgDocument
  5import OrgHighlight
  6import OrgPresentation
  7import UIKit
  8
  9/// The iOS editor: a TextKit 2 text view that is the open file's live state, as the Mac's
 10/// `OrgEditor` is. Typing and undo go through the text view and into the document; commands
 11/// run on the document and apply their edits as one undo step; headings, drawers and blocks
 12/// fold as TAB cycles them.
 13@MainActor
 14final class MobileEditor: NSObject, DocumentBuffer {
 15    /// One highlighter for every editor and the reader: it caches compiled grammars and results.
 16    static let highlighter = TreeSitterHighlighter()
 17    private(set) var document: DocumentState
 18    /// The views showing the buffer, one per pane; the first is made with the editor.
 19    private(set) var textViews: [UITextView]
 20    /// The view with focus, or the last to have had it: the one commands act on.
 21    private(set) var textView: UITextView
 22    var options: EditingOptions = .org {
 23        didSet {
 24            if options.spellCheck != oldValue.spellCheck { restyleAll() }
 25            if !showMarkup, options.hideEmphasisMarkers != oldValue.hideEmphasisMarkers || options.prettyEntities != oldValue.prettyEntities {
 26                restyleAll()
 27            }
 28        }
 29    }
 30    /// Colors and type; a change, or a new Dynamic Type size, restyles the file.
 31    var themeSpec: ThemeSpec {
 32        get { theme.spec }
 33        set {
 34            let new = MobileTheme(newValue)
 35            guard new.spec != theme.spec || new.font != theme.font || new.body != theme.body else { return }
 36            theme = new
 37            paragraphStyles = [:]
 38            applyThemeToView()
 39            restyleAll()
 40        }
 41    }
 42    /// Link brackets and targets, and emphasis markers when `org-hide-emphasis-markers` hides
 43    /// them, shown. Hidden markup shows on the caret's line, so it can be edited.
 44    var showMarkup = true {
 45        didSet { if showMarkup != oldValue { restyleAll() } }
 46    }
 47    /// An incremental search in progress, and the last search string, for C-s C-s.
 48    var isearch: ISearch?
 49    static var lastISearch: String?
 50    /// `auto-fill-mode` for this buffer: the settings' unless toggled here.
 51    var autoFillOverride: Bool?
 52    var autoFills: Bool { autoFillOverride ?? options.autoFill }
 53    var keymap = KeymapPreset.emacs.keymap {
 54        didSet { dispatcher = KeyDispatcher(keymap: keymap) }
 55    }
 56    /// The Doom preset's modal editing, and its state: the engine, the caret in visual
 57    /// states, marks, the jump list, what insert state began with, and macros.
 58    var modal = false {
 59        didSet {
 60            if modal != oldValue { vim = Vim() }
 61            updateCursor()
 62        }
 63    }
 64    var vim = Vim()
 65    var visualCaret: Int?
 66    var vimMarks: [Character: Int] = [:]
 67    var jumpList: [Int] = []
 68    var jumpIndex = 0
 69    var insertSnapshot: String?
 70    var recordingRegister: Character?
 71    var recordedKeys: [KeyChord] = []
 72    var replayingMacro = 0
 73    /// Keyboard macros: the keys left in the one being replayed, how deep replays are nested,
 74    /// the error that stops them, the key that runs the last one again right after (`e` after
 75    /// C-x e), and the keys of the command running, nil when it didn't come from keys.
 76    var macroKeys: [KeyChord] = []
 77    var kmacroDepth = 0
 78    var macroError: String?
 79    var macroRepeatKey: KeyChord?
 80    var commandKeys: [KeyChord]?
 81    /// Named macros (`macros.toml`).
 82    var namedMacros = NamedMacros.shared
 83    static var vimRegisters: [Character: (text: String, linewise: Bool)] = [:]
 84    static var vimClipboardRecord: (text: String, linewise: Bool)?
 85    static var macros: [Character: [KeyChord]] = [:]
 86    /// What `:`, `/` and `?` read, oldest first, for `q:`.
 87    static var promptHistory: [String: [String]] = [:]
 88    /// The last `:s`, for `&` and `g&`.
 89    static var lastSubstitute: (pattern: String, replacement: String, flags: String)?
 90    /// The file's path, for the `%` register.
 91    var fileName: String?
 92    var onChange: (() -> Void)?
 93    var onMessage: ((String) -> Void)?
 94    var onPrompt: ((Prompt, @escaping (String?) -> Void) -> Void)?
 95    var onLink: ((OrgLink) -> Void)?
 96    /// Edits being applied, which the typing hooks leave alone.
 97    private var applyingEdits = false
 98    /// Source blocks to write to their files (C-c C-v t).
 99    var onTangle: ((Tangle.Scope) -> Void)?
100    /// A source block to run (C-c C-c).
101    var onBabel: ((BabelJob) -> Void)?
102    /// The file's setup files to read again (C-c C-c on a keyword line).
103    var onRefreshSetup: (() -> Void)?
104    /// A block, a table's formulas or a field to edit apart (C-c ', C-c `).
105    var onEditBlock: ((BlockEdit) -> Void)?
106    /// A followed timestamp's agenda days: the first (a `Days` number) and how many.
107    var onAgenda: ((Int, Int) -> Void)?
108    /// Shows a column view.
109    var onColumnView: ((ColumnView.View) -> Void)?
110    /// Commands the app runs, as `app.clock.in`.
111    var onAppCommand: ((String) -> Void)?
112    /// Where paste looks for an image; scripts checking the app set another.
113    static var pasteboard = UIPasteboard.general
114    /// Files dropped at the caret; nil leaves them to the text view.
115    var onFiles: (([URL]) -> Void)?
116    /// An image pasted at the caret, with its extension (`yank-media`).
117    var onImage: ((Data, String) -> Void)?
118    /// Tags used across the workspace, for completion.
119    var knownTags: @Sendable () -> [String] = { [] }
120
121    var theme: MobileTheme
122    var fold = FoldState()
123    var globalVisibility: GlobalVisibility?
124    let hidden = LockedRanges()
125    /// An arrow key moved the caret, and where it was before; the caret skips folds then.
126    var movedByArrow = false
127    var previousCaret = 0
128    /// Blocks drawn on a band.
129    let shaded = LockedRanges()
130    let fragmentStyle = FragmentStyle()
131    var selectionColor: UIColor = .clear
132    /// `org-indent-mode` and `org-hide-leading-stars`, from the settings and `#+STARTUP`.
133    var indented = true
134    var hideStars = false
135    /// One paragraph style per indent pair.
136    var paragraphStyles: [[Int]: NSParagraphStyle] = [:]
137    /// `SpellCheck.skipped` for a revision of the buffer.
138    var spellSkipCache: (revision: Int, ranges: [Range<Int>])?
139    /// The line last revealed while markup is hidden, to hide again when the caret leaves.
140    var revealedLine: NSRange?
141    /// `org-toggle-inline-images`: image links show their image.
142    var showsImages = false
143    /// Links with a description show their image too.
144    var imagesIncludeLinked = false
145    /// `org-latex-preview`: LaTeX fragments show as typeset math.
146    var showsLatex = false
147    /// The view width images were last sized for.
148    var imageWidth: CGFloat = 0
149    /// The text width heading tag gaps were last drawn for, and whether drawing them again is waiting.
150    var tagGapWidth: CGFloat = 0
151    var fittingTagGaps = false
152    /// The file's folder, for relative image paths.
153    let baseDirectory: URL?
154    /// An `attachment:` link's file, from its name, offset and the tree; nil leaves those links
155    /// as text.
156    var attachmentPath: ((String, Int, OrgTree) -> String?)?
157    static let imageCache = NSCache<NSString, UIImage>()
158    var loading = false
159    var restyleScheduled: Range<Int>?
160    /// An edit since the last restyle touched a line that can start or end a block.
161    var blocksMayChange = false
162    /// Text before its end is styled; after it, the text waits for the background passes.
163    var styled = StyledExtent()
164    var stylingScheduled = false
165    /// Narrowed table columns (`org-table-shrink`).
166    var shrunk = ShrunkColumns()
167    /// A command's edits being applied, which keep shrunk columns narrow.
168    private var commandEditing = false
169    /// The snippet whose fields are being filled in, and the range drawn for it last.
170    var snippetSession: SnippetSession?
171    var snippetHighlight: Range<Int>?
172    var updatingMirrors = false
173
174    init(
175        document: DocumentState, editable: Bool, options: EditingOptions = .org, theme spec: ThemeSpec = .default,
176        showMarkup: Bool = true, baseDirectory: URL? = nil
177    ) {
178        self.document = document
179        self.options = options
180        self.showMarkup = showMarkup
181        self.baseDirectory = baseDirectory
182        theme = MobileTheme(spec)
183        let keyed = KeyedTextView(usingTextLayoutManager: true)
184        textView = keyed
185        textViews = [keyed]
186        super.init()
187        configure(keyed, editable: editable)
188        textView.textStorage.delegate = self
189        (textView.textLayoutManager?.textContentManager as? NSTextContentStorage)?.delegate = self
190        let startup = Presentation.startupDisplay(document.tree, options: options)
191        indented = startup.indented
192        hideStars = startup.hideStars
193        showsImages = startup.inlineImages
194        showsLatex = startup.latexPreview
195        shrunk = ShrunkColumns.startup(document.tree)
196        applyThemeToView()
197        load(document.text)
198        setFolds(startup.folds)
199        if startup.alignTables { _ = perform(AlignAllTables()) }
200        truncatesLines = startup.truncated
201        textView.selectedRange = NSRange(location: 0, length: 0)
202    }
203
204    /// What every view of the buffer has: the keymap, the editor as its delegates and the fold
205    /// tap. Views in one scene share its undo stack.
206    private func configure(_ view: KeyedTextView, editable: Bool) {
207        view.keyHandler = { [weak self, weak view] key in
208            guard let self else { return false }
209            if let view { focus(view) }
210            return handleKey(key)
211        }
212        view.onLayout = { [weak self] in self?.viewResized() }
213        let find = EditorFind(view: view) { [weak self] in self?.unfold(around: $0) }
214        view.find = find
215        view.addInteraction(UIFindInteraction(sessionDelegate: find))
216        view.onFiles = { [weak self, weak view] files in
217            guard let self, let onFiles else { return false }
218            if let view { focus(view) }
219            onFiles(files)
220            return true
221        }
222        view.onImage = { [weak self, weak view] data, ext in
223            guard let self, let onImage else { return false }
224            if let view { focus(view) }
225            onImage(data, ext)
226            return true
227        }
228        view.textDropDelegate = view
229        view.isEditable = editable
230        view.autocorrectionType = .no
231        view.autocapitalizationType = .none
232        view.smartQuotesType = .no
233        view.smartDashesType = .no
234        view.smartInsertDeleteType = .no
235        // The editor checks spelling itself, outside code, links and keywords.
236        view.spellCheckingType = .no
237        view.keyboardDismissMode = .interactive
238        view.alwaysBounceVertical = true
239        view.textContainerInset = UIEdgeInsets(top: 12, left: 8, bottom: 24, right: 8)
240        view.delegate = self
241        view.textLayoutManager?.delegate = self
242        let foldTap = UITapGestureRecognizer(target: self, action: #selector(tappedFold))
243        foldTap.delegate = self
244        view.addGestureRecognizer(foldTap)
245    }
246
247    // MARK: - Views
248
249    /// Another view of the buffer, for another pane: its own layout manager on the buffer's
250    /// content storage, so text, folds and styles are shared and the caret and scroll aren't.
251    func addView() -> UITextView {
252        guard let storage = textViews[0].textLayoutManager?.textContentManager as? NSTextContentStorage else { return textViews[0] }
253        let manager = NSTextLayoutManager()
254        manager.delegate = self
255        let container = NSTextContainer(size: CGSize(width: 0, height: CGFloat.greatestFiniteMagnitude))
256        manager.textContainer = container
257        storage.addTextLayoutManager(manager)
258        let view = KeyedTextView(frame: .zero, textContainer: container)
259        configure(view, editable: textViews[0].isEditable)
260        textViews.append(view)
261        applyThemeToView(view)
262        if truncatesLines { view.truncates = true }
263        updateCursor()
264        return view
265    }
266
267    /// Drops a view `addView` made; the first stays with the editor.
268    func removeView(_ view: UITextView) {
269        guard view !== textViews[0], let index = textViews.firstIndex(where: { $0 === view }) else { return }
270        textViews.remove(at: index)
271        if let manager = view.textLayoutManager, let storage = manager.textContentManager { storage.removeTextLayoutManager(manager) }
272        view.delegate = nil
273        onFocus[ObjectIdentifier(view)] = nil
274        if textView === view { textView = textViews[0] }
275    }
276
277    /// What each view's screen does when its view takes focus: the editor's callbacks are
278    /// that screen's from then on.
279    var onFocus: [ObjectIdentifier: () -> Void] = [:]
280
281    /// Commands act on `view` from now on.
282    func focus(_ view: UITextView) {
283        guard view !== textView, textViews.contains(where: { $0 === view }) else { return }
284        textView = view
285        onFocus[ObjectIdentifier(view)]?()
286    }
287
288    /// Every view's layout manager.
289    var layoutManagers: [NSTextLayoutManager] { textViews.compactMap(\.textLayoutManager) }
290
291    // MARK: - DocumentBuffer
292
293    var selection: [Range<Int>] {
294        let selected = textView.selectedRange
295        return [selected.location..<NSMaxRange(selected)]
296    }
297
298    func update<T>(_ change: (inout DocumentState) throws -> T) rethrows -> T {
299        let before = document.text
300        let defaultsBefore = document.defaults
301        let selected = textView.selectedRange
302        let result = try change(&document)
303        if document.text != before {
304            // A save that merged a change from disk, or a revert: the view shows the new text.
305            shrunk = ShrunkColumns()
306            load(document.text)
307            let length = (document.text as NSString).length
308            textView.selectedRange = NSRange(location: min(selected.location, length), length: 0)
309            textView.undoManager?.removeAllActions()
310            setFolds(fold)
311        } else if document.defaults != defaultsBefore {
312            restartStyling()
313        }
314        return result
315    }
316
317    func perform(_ command: any OrgCommand, now: Date = Date(), answers: [String: String] = [:]) -> CommandStep {
318        let context = EditContext(
319            revision: document.revision, text: document.text, tree: document.tree, selection: selection,
320            now: now, answers: answers, hidden: hidden.all, options: options, knownTags: knownTags
321        )
322        let step = command.run(in: context)
323        switch step {
324        case .commit(let result):
325            guard textView.isEditable || result.edits.isEmpty else {
326                fail("This file is read-only.")
327                return .failed("read-only")
328            }
329            commandEditing = true
330            applyEdits(result.edits)
331            commandEditing = false
332            if let selected = result.selection?.first {
333                unfold(around: selected.lowerBound)
334                textView.selectedRange = NSRange(location: selected.lowerBound, length: selected.count)
335                textView.scrollRangeToVisible(textView.selectedRange)
336            }
337            for effect in result.effects {
338                switch effect {
339                case .message(let text): onMessage?(text)
340                case .fold(let start):
341                    var state = fold
342                    state.folds.insert(start)
343                    setFolds(state)
344                case .refreshSetup: onRefreshSetup?()
345                case .timer(let timer): TimerModel.shared.set(timer)
346                case .snippet(let session): startSnippet(session)
347                default: break
348                }
349            }
350        case .failed(let message):
351            fail(message)
352        case .prompt(let prompt):
353            ask(prompt) { [weak self] answer in
354                guard let self else { return }
355                guard let answer else { return self.onMessage?("Quit") ?? () }
356                _ = self.perform(command, now: now, answers: answers.merging([prompt.key: answer]) { $1 })
357            }
358        case .external(.editBlock(let edit)) where onEditBlock != nil:
359            onEditBlock?(edit)
360        case .external(.babel(let job)) where onBabel != nil:
361            onBabel?(job)
362        case .external(.tangle(let scope)) where onTangle != nil:
363            onTangle?(scope)
364        case .external(.agenda(let start, let count)) where onAgenda != nil:
365            onAgenda?(start, count)
366        case .external(.columnView(let view)) where onColumnView != nil:
367            onColumnView?(view)
368        case .external(let request):
369            // The fields written before a formula only Emacs can do stay, as Emacs leaves them
370            // when a formula fails.
371            if case .emacsTable(_, _, _, _, _, _, let partial?) = request { _ = perform(PrecomputedEdit(partial)) }
372            // `org-sbe` without Babel shows its paywall.
373            if case .emacsTable(_, _, _, TableBlocks.lockedReason, _, _, _) = request {
374                ProAccess.shared.allows(.babel)
375                return step
376            }
377            onMessage?(Self.unavailable(request, title: command.title))
378        }
379        return step
380    }
381
382    /// Why a request the app doesn't handle did nothing: only table recalculation needs Emacs.
383    static func unavailable(_ request: ExternalRequest, title: String) -> String {
384        if case .emacsTable(_, _, _, let reason, _, let formula?, _) = request {
385            return String(localized: "The table was recalculated up to \(formula), which needs Emacs on the Mac: \(TableReason.localized(reason)).", comment: "Table formulas calculated up to one only Emacs can calculate")
386        }
387        if case .emacsTable(_, _, _, let reason, _, _, _) = request {
388            return String(localized: "This table needs Emacs, which runs on the Mac: \(TableReason.localized(reason)).", comment: "Table formulas only Emacs can calculate")
389        }
390        return unavailable(title)
391    }
392
393    /// The refusal for a command that runs on the Mac and not here, by its title.
394    static func unavailable(_ title: String) -> String {
395        String(localized: "\(CommandTitle.localized(title)) isn't available on iPhone and iPad. It runs on the Mac.", comment: "A command that runs only on the Mac")
396    }
397
398    /// The refusal for a command identifier, named by its title where the app knows one.
399    static func unavailable(command id: String) -> String {
400        unavailable(Commands.command(id)?.title ?? CommandPalette.viewCommands.first { $0.id == id }?.title ?? id)
401    }
402
403    // MARK: - Commands by name and key
404
405    /// Runs what `keys` (as `C-c C-t`) is bound to in the Emacs keymap, for the caret's context.
406    func run(keys: String) {
407        guard let chords = KeySequence.parse(keys) else { return }
408        let context = editContext()
409        let binding = keymap.candidates(for: chords).first { binding in
410            (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
411        }
412        guard let binding else { return onMessage?("Nothing to do here") ?? () }
413        run(binding.command)
414    }
415
416    func run(_ id: String) {
417        if let snippet = Snippets.command(id) {
418            _ = perform(snippet)
419            return
420        }
421        switch id {
422        case "org.snippet.next-field": nextSnippetField()
423        case "org.snippet.previous-field": previousSnippetField()
424        case "org.cycle":
425            if !cycleAtCaret() { onMessage?("Not on a heading, drawer or block") }
426        case "org.cycle-global": cycleGlobal()
427        case _ where id.hasPrefix("org.fold."): foldCommand(id)
428        case "org.link.open": openLinkAtCaret()
429        case "org.toggle-inline-images": toggleImages()
430        case "org.toggle-inline-images-linked": toggleImages(includeLinked: true)
431        case "org.latex-preview": toggleLatex()
432        case "editor.toggle-truncate-lines":
433            truncatesLines.toggle()
434            onMessage?(truncatesLines ? "Truncate long lines enabled" : "Truncate long lines disabled")
435        case "edit.isearch-forward": startISearch(forward: true)
436        case "edit.isearch-backward": startISearch(forward: false)
437        case "edit.isearch-forward-regexp": startISearch(forward: true, regexp: true)
438        case "edit.isearch-backward-regexp": startISearch(forward: false, regexp: true)
439        case "editor.toggle-auto-fill":
440            autoFillOverride = !autoFills
441            onMessage?(autoFills ? "Auto-Fill mode enabled in current buffer" : "Auto-Fill mode disabled in current buffer")
442        case "edit.undo": textView.undoManager?.undo()
443        case "edit.redo": textView.undoManager?.redo()
444        case "org.table.toggle-column-width", "org.table.shrink", "org.table.expand": tableColumnWidth(id)
445        case _ where id.hasPrefix("macro."): macroCommand(id)
446        case _ where id.hasPrefix("app.") || Self.linkCommands.contains(id):
447            if let onAppCommand { onAppCommand(id) } else { onMessage?(Self.unavailable(command: id)) }
448        default:
449            if let command = Commands.command(id) {
450                _ = perform(command)
451            } else {
452                fail(Self.unavailable(command: id))
453            }
454        }
455    }
456
457    /// Link commands that need the stored links or the file, which the screen has.
458    static let linkCommands: Set<String> = ["org.link.store", "org.id.store-link", "org.link.insert"]
459
460    func applies(_ id: String, in context: EditContext) -> Bool {
461        if let command = Commands.command(id) ?? Snippets.command(id) { return command.applies(in: context) }
462        switch id {
463        case "org.snippet.next-field", "org.snippet.previous-field": return snippetSession != nil
464        case "org.cycle":
465            return Presentation.heading(containing: context.caret, in: context.tree) != nil || Wrappers.toggleable(at: context.caret, in: context.tree) != nil
466        case _ where id.hasPrefix("org.fold."): return true
467        case "org.cycle-global", "edit.undo", "edit.redo", "org.toggle-inline-images", "org.toggle-inline-images-linked", "org.latex-preview", "editor.toggle-truncate-lines",
468             "editor.toggle-auto-fill", "edit.isearch-forward", "edit.isearch-backward",
469             "edit.isearch-forward-regexp", "edit.isearch-backward-regexp": return true
470        case "app.clock.in", "app.clock.out", "app.clock.cancel", "app.clock.goto", "app.clock.in-recent", "app.clock.in-last",
471             "app.clock.goto-recent", "app.clock.default", "app.clock.resolve", "app.toggle-markup": return onAppCommand != nil
472        case "app.refile.goto", "app.table-import", "app.crypt.encrypt-entries", "app.crypt.forget-passphrase", "app.attach.attach", "app.attach.url",
473             "app.attach.new", "app.attach.open", "app.attach.reveal", "app.attach.delete", "app.attach.delete-all", "app.attach.sync",
474             "app.attach.set-directory", "app.attach.unset-directory", "app.backlinks", "app.node.find", "app.node.insert",
475             "app.node.rename-from-front-matter": return onAppCommand != nil
476        case _ where id.hasPrefix("app.node."): return onAppCommand != nil
477        case _ where id.hasPrefix("app.dailies."): return onAppCommand != nil
478        case "app.crypt.encrypt-entry": return onAppCommand != nil && OrgCrypt.heading(context.text, at: context.caret) != nil && OrgCrypt.encryptedRange(context.text, at: context.caret) == nil
479        case "app.crypt.open-entry", "app.crypt.decrypt-entry": return onAppCommand != nil && OrgCrypt.encryptedRange(context.text, at: context.caret) != nil
480        case "app.table-export", "app.plot": return onAppCommand != nil && ImportTable.exportText(context.text, at: context.caret, path: "") != nil
481        case "app.refile", "app.refile.copy", "app.archive": return onAppCommand != nil && Presentation.heading(containing: context.caret, in: context.tree) != nil
482        case "app.copy-rich-text", "app.export.html-open", "app.export-body-only", "app.export.icalendar-agenda", "app.export.icalendar-combined": return onAppCommand != nil
483        case _ where id.hasPrefix("app.publish"): return onAppCommand != nil
484        case _ where Self.linkCommands.contains(id): return onAppCommand != nil
485        case "org.link.open": return OpenLinkAtPoint().applies(in: context)
486        case "org.table.toggle-column-width", "org.table.shrink", "org.table.expand":
487            return TableShrink.table(at: context.caret, in: context.text) != nil
488        default: return false
489        }
490    }
491
492    // MARK: - Hardware keyboard
493
494    lazy var dispatcher = KeyDispatcher(keymap: keymap)
495
496    private static let named: [UIKeyboardHIDUsage: String] = [
497        .keyboardTab: "TAB", .keyboardReturnOrEnter: "RET", .keypadEnter: "RET", .keyboardSpacebar: "SPC",
498        .keyboardEscape: "ESC", .keyboardDeleteOrBackspace: "DEL", .keyboardDeleteForward: "<delete>",
499        .keyboardLeftArrow: "<left>", .keyboardRightArrow: "<right>", .keyboardUpArrow: "<up>", .keyboardDownArrow: "<down>",
500        .keyboardHome: "<home>", .keyboardEnd: "<end>", .keyboardPageUp: "<prior>", .keyboardPageDown: "<next>",
501    ]
502
503    /// A key press as a chord; Option is Meta, as `option-as-meta` makes it on the Mac.
504    static func chord(_ key: UIKey) -> KeyChord? {
505        var modifiers: KeyChord.Modifiers = []
506        let flags = key.modifierFlags
507        if flags.contains(.control) { modifiers.insert(.control) }
508        if flags.contains(.alternate) { modifiers.insert(.meta) }
509        if flags.contains(.command) { modifiers.insert(.command) }
510        if let name = named[key.keyCode] {
511            if flags.contains(.shift) { modifiers.insert(.shift) }
512            return KeyChord(name, modifiers)
513        }
514        var characters = key.charactersIgnoringModifiers
515        if flags.contains(.shift), characters.count == 1, characters.lowercased() == characters { characters = characters.uppercased() }
516        guard characters.count == 1 else { return nil }
517        return KeyChord(characters, modifiers)
518    }
519
520    /// The Emacs keymap's commands on an iPad keyboard. Keys it doesn't bind, Command shortcuts
521    /// and editing keys (C-a, C-e, C-k...) are the text system's.
522    func handleKey(_ key: UIKey) -> Bool {
523        movedByArrow = [.keyboardUpArrow, .keyboardDownArrow, .keyboardLeftArrow, .keyboardRightArrow].contains(key.keyCode)
524        guard let chord = Self.chord(key), !chord.modifiers.contains(.command) else { return false }
525        return handleChord(chord)
526    }
527
528    /// A key, typed or replayed from a keyboard macro. False lets the text system have it.
529    func handleChord(_ chord: KeyChord) -> Bool {
530        if kmacroDepth == 0 { Self.kmacro.record(chord, begins: dispatcher.pending.isEmpty) }
531        if let key = macroRepeatKey {
532            macroRepeatKey = nil
533            if chord == key, dispatcher.pending.isEmpty, isearch == nil {
534                callLastMacro(count: 1, repeatKey: key)
535                return true
536            }
537        }
538        if isearch != nil, isearchKey(chord) { return true }
539        if let handled = snippetKey(chord) { return handled }
540        if modal { return handleModal(chord) }
541        // Option alone types characters unless it begins a binding.
542        if chord.modifiers == [.meta], dispatcher.pending.isEmpty,
543           keymap.candidates(for: [chord]).isEmpty, !keymap.isPrefix([chord]) { return false }
544        switch dispatcher.feed(chord) {
545        case .pending(let keys):
546            onMessage?(KeySequence.format(keys) + "-")
547            return true
548        case .cancelled:
549            fail("Quit")
550            return true
551        case .undefined(let keys):
552            fail("\(KeySequence.format(keys)) is undefined")
553            return true
554        case .unbound:
555            return snippetTab(chord)
556        case .complete(let keys, let candidates):
557            let context = editContext()
558            let runnable = candidates.first { binding in
559                (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
560            }
561            // A sequence runs its command even where it doesn't apply, which says why, as on the Mac.
562            let argument = dispatcher.argument != nil
563            guard let binding = runnable ?? (keys.count > 1 || argument ? candidates.first : nil) else { return keys.count == 1 && !argument && snippetTab(chord) }
564            // A prefix argument (C-u, C-u 3) counts keyboard macros only.
565            if argument, !binding.command.hasPrefix("macro.") {
566                fail("\(KeySequence.format(keys)) doesn't take a prefix argument")
567                return true
568            }
569            if keys.count == 1, binding.command.hasPrefix("edit."), !["edit.undo", "edit.redo"].contains(binding.command) { return false }
570            commandKeys = keys
571            defer { commandKeys = nil }
572            run(binding.command)
573            return true
574        }
575    }
576
577    func editContext() -> EditContext {
578        EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: selection, hidden: hidden.all, options: options, knownTags: knownTags)
579    }
580
581    private func openLinkAtCaret() {
582        let caret = textView.selectedRange.location
583        if let link = Links.link(at: caret, text: document.text, tree: document.tree)?.link {
584            onLink?(link)
585        } else if let days = Links.timestampDays(at: caret, text: document.text) {
586            onAgenda?(days.start, days.count)
587        } else {
588            onMessage?("No link here")
589        }
590    }
591
592    // MARK: - Editing
593
594    /// Applies `edits` (against the current text) through the text view as one undo step.
595    func applyEdits(_ edits: [TextEdit]) {
596        let interval = Perf.begin("editor.applyEdits")
597        defer { interval.end() }
598        guard !edits.isEmpty else { return }
599        applyingEdits = true
600        defer { applyingEdits = false }
601        // Straight into the storage: replacing through text input would take the active
602        // keyboard's substitutions (smart dashes) when another view has the keyboard.
603        let storage = textView.textStorage
604        let old = storage.string as NSString
605        // By lines, so a fold between two changes stays.
606        let ascending = edits.flatMap { splitByLines($0, in: storage.string) }.sorted { $0.range.lowerBound < $1.range.lowerBound }
607        var inverse: [TextEdit] = []
608        var delta = 0
609        for edit in ascending {
610            let start = edit.range.lowerBound + delta
611            let length = (edit.replacement as NSString).length
612            inverse.append(TextEdit(range: start..<start + length, replacement: old.substring(with: NSRange(edit.range))))
613            delta += length - edit.range.count
614        }
615        let caret = textView.selectedRange
616        // One at a time, last first: each is processed alone, so folds between them stay.
617        for edit in ascending.reversed() {
618            storage.replaceCharacters(in: NSRange(edit.range), with: edit.replacement)
619        }
620        textView.undoManager?.registerUndo(withTarget: self) { editor in
621            editor.applyEdits(inverse)
622            editor.textView.selectedRange = caret
623        }
624    }
625
626    /// The storage changed (typing, a command, undo): the document takes the same edit, and
627    /// folds and styles follow.
628    fileprivate func storageEdited(range: NSRange, delta: Int) {
629        let interval = Perf.begin("editor.edit")
630        defer { interval.end() }
631        guard !loading else { return }
632        let old = range.location..<(range.location + range.length - delta)
633        let replacement = (textView.textStorage.string as NSString).substring(with: range)
634        let edit = TextEdit(range: old, replacement: replacement)
635        snippetEdited(edit)
636        let oldTree = document.tree
637        let oldText = document.text as NSString
638        do {
639            try document.apply([edit], baseRevision: document.revision)
640        } catch {
641            // Out of step: the view's text wins.
642            shrunk = ShrunkColumns()
643            load(textView.textStorage.string)
644            return
645        }
646        let newText = textView.textStorage.string as NSString
647        styled.map(through: edit, in: newText)
648        let affected = Presentation.restyleRange(for: edit, old: (oldTree, oldText), new: (document.tree, newText))
649        vim.changed(edit)
650        // Walking the tree for blocks costs more than typing; only an edit on a line that could
651        // start or end one needs it, others move the ranges.
652        let newEnd = edit.range.lowerBound + (replacement as NSString).length
653        if Presentation.mayChangeBlocks(oldText, edit.range) || Presentation.mayChangeBlocks(newText, edit.range.lowerBound..<newEnd) {
654            blocksMayChange = true
655        } else {
656            shaded.set(ViewState(selection: shaded.all).mapped(through: [edit]).selection, folded: [])
657        }
658        for table in shrunk.map(through: edit, in: textView.textStorage.string, command: commandEditing) { scheduleRestyle(table) }
659        fold = FoldState(
660            folds: Self.map(fold.folds, old, delta), bodyFolds: Self.map(fold.bodyFolds, old, delta),
661            wrapperFolds: Self.map(fold.wrapperFolds, old, delta)
662        )
663        scheduleRestyle(affected.lowerBound..<min(affected.upperBound, newText.length))
664        onChange?()
665    }
666
667    /// Starts after the edit move with it; ones inside it go.
668    static func map(_ starts: Set<Int>, _ old: Range<Int>, _ delta: Int) -> Set<Int> {
669        Set(starts.compactMap { start in
670            if start >= old.upperBound { return start + delta }
671            return start <= old.lowerBound ? start : nil
672        })
673    }
674
675}
676
677extension MobileEditor: UITextViewDelegate {
678    func textViewDidBeginEditing(_ textView: UITextView) {
679        focus(textView)
680    }
681
682    /// Another view's caret moves with edits made in this one; only the focused view's
683    /// selection drives the display.
684    func textView(_ textView: UITextView, editMenuForTextIn range: NSRange, suggestedActions: [UIMenuElement]) -> UIMenu? {
685        options.spellCheck ? spellingMenu(for: range, in: textView, suggested: suggestedActions) : nil
686    }
687
688    func textViewDidChangeSelection(_ textView: UITextView) {
689        if textView.isFirstResponder { focus(textView) }
690        guard textView === self.textView else { return }
691        selectionChanged()
692    }
693
694    /// `electric-pair-mode` for typed brackets and quotes, DEL and RET, and `auto-fill-mode`
695    /// for a typed space, from either keyboard.
696    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
697        if isearch != nil, !applyingEdits {
698            isearchTyped(text)
699            return false
700        }
701        if !applyingEdits { typedOutsideInsert() }
702        if autoFills, !applyingEdits, textView.markedTextRange == nil, text == " ", range == textView.selectedRange {
703            _ = perform(AutoFillSpace())
704            return false
705        }
706        guard options.electricPair, !applyingEdits, textView.markedTextRange == nil else { return true }
707        let selected = textView.selectedRange
708        let key: String
709        if text.isEmpty, selected.length == 0, range.length == 1, NSMaxRange(range) == selected.location {
710            key = "DEL"
711        } else if range == selected, text == "\n" {
712            key = "RET"
713        } else if range == selected, ElectricPairKey.characters.contains(text) {
714            key = text
715        } else {
716            return true
717        }
718        let command = ElectricPairKey(key: key)
719        guard command.applies(in: editContext()) else { return true }
720        _ = perform(command)
721        return false
722    }
723}
724
725extension MobileEditor: UIGestureRecognizerDelegate {
726    /// The drawer or block a tap at `point` folds or unfolds: a folded one's `…`, the space after
727    /// its first line, or anywhere on an open drawer's first line.
728    private func foldToggle(at point: CGPoint, in view: UITextView? = nil) -> Int? {
729        let textView = view ?? textView
730        guard let manager = textView.textLayoutManager, let content = manager.textContentManager else { return nil }
731        let inContainer = CGPoint(x: point.x - textView.textContainerInset.left, y: point.y - textView.textContainerInset.top)
732        guard let fragment = manager.textLayoutFragment(for: inContainer), let range = fragment.textElement?.elementRange else { return nil }
733        let start = content.offset(from: content.documentRange.location, to: range.location)
734        guard let line = fragment.textLineFragments.first(where: { $0.characterRange.length > 0 }) ?? fragment.textLineFragments.first else { return nil }
735        if hidden.isFolded(start) { return inContainer.x - fragment.layoutFragmentFrame.minX >= line.typographicBounds.maxX ? start : nil }
736        guard Wrappers.starting(at: start, in: document.tree)?.kind == .drawer,
737              inContainer.y - fragment.layoutFragmentFrame.minY < line.typographicBounds.maxY else { return nil }
738        return start
739    }
740
741    /// A tap on a fold's `…` opens it, and one on an open drawer's first line folds it, as TAB
742    /// on the line does.
743    @objc fileprivate func tappedFold(_ tap: UITapGestureRecognizer) {
744        if let view = tap.view as? UITextView { focus(view) }
745        guard let start = foldToggle(at: tap.location(in: textView)),
746              let next = Presentation.cycle(at: start, in: document.tree, fold) else { return }
747        setFolds(next)
748    }
749
750    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
751        guard let view = gestureRecognizer.view as? UITextView else { return false }
752        return foldToggle(at: gestureRecognizer.location(in: view), in: view) != nil
753    }
754
755    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer) -> Bool {
756        true
757    }
758}
759
760extension MobileEditor: NSTextStorageDelegate {
761    nonisolated func textStorage(
762        _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorage.EditActions, range editedRange: NSRange, changeInLength delta: Int
763    ) {
764        guard editedMask.contains(.editedCharacters) else { return }
765        MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
766    }
767}
768
769extension MobileEditor: NSTextContentStorageDelegate {
770    /// Folded text isn't enumerated, so it isn't laid out or drawn.
771    nonisolated func textContentManager(
772        _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
773    ) -> Bool {
774        guard let range = textElement.elementRange else { return true }
775        let documentStart = textContentManager.documentRange.location
776        let start = textContentManager.offset(from: documentStart, to: range.location)
777        let end = textContentManager.offset(from: documentStart, to: range.endLocation)
778        return !hidden.covers(start, end)
779    }
780}
781
782extension MobileEditor: NSTextLayoutManagerDelegate {
783    /// Folded headings, drawers and blocks end with `…`; blocks are on a band; image links
784    /// show their image; pretty entities draw their character.
785    nonisolated func textLayoutManager(
786        _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
787    ) -> NSTextLayoutFragment {
788        let range = textElement.elementRange
789        guard let range, let manager = textLayoutManager.textContentManager else { return NSTextLayoutFragment(textElement: textElement, range: range) }
790        let offset = manager.offset(from: manager.documentRange.location, to: range.location)
791        let folded = hidden.isFolded(offset)
792        let band = shaded.containing(offset) != nil ? fragmentStyle.blockBand : nil
793        let string = (textElement as? NSTextParagraph)?.attributedString
794        let image = string.map(OrgLineFragment.hasImages) ?? false
795        let entities = string.map(OrgLineFragment.hasEntities) ?? false
796        let latex = string.map(OrgLineFragment.hasLatex) ?? false
797        guard folded || band != nil || image || entities || latex else { return NSTextLayoutFragment(textElement: textElement, range: range) }
798        let fragment = OrgLineFragment(textElement: textElement, range: range)
799        fragment.folded = folded
800        fragment.band = band
801        if band != nil {
802            fragment.start = offset
803            fragment.style = fragmentStyle
804        }
805        return fragment
806    }
807}
808#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