Sources/OrgstarMobile/MobileEditor.swift

672 lines · 33135 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            for view in textViews { view.spellCheckingType = options.spellCheck ? .yes : .no }
 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 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    static var vimRegisters: [Character: (text: String, linewise: Bool)] = [:]
 74    static var vimClipboardRecord: (text: String, linewise: Bool)?
 75    static var macros: [Character: [KeyChord]] = [:]
 76    /// What `:`, `/` and `?` read, oldest first, for `q:`.
 77    static var promptHistory: [String: [String]] = [:]
 78    var onChange: (() -> Void)?
 79    var onMessage: ((String) -> Void)?
 80    var onPrompt: ((Prompt, @escaping (String?) -> Void) -> Void)?
 81    var onLink: ((OrgLink) -> Void)?
 82    /// Edits being applied, which the typing hooks leave alone.
 83    private var applyingEdits = false
 84    /// Source blocks to write to their files (C-c C-v t).
 85    var onTangle: ((Tangle.Scope) -> Void)?
 86    /// A source block to run (C-c C-c).
 87    var onBabel: ((BabelJob) -> Void)?
 88    /// The file's setup files to read again (C-c C-c on a keyword line).
 89    var onRefreshSetup: (() -> Void)?
 90    /// A block, a table's formulas or a field to edit apart (C-c ', C-c `).
 91    var onEditBlock: ((BlockEdit) -> Void)?
 92    /// A followed timestamp's agenda days: the first (a `Days` number) and how many.
 93    var onAgenda: ((Int, Int) -> Void)?
 94    /// Shows a column view.
 95    var onColumnView: ((ColumnView.View) -> Void)?
 96    /// Commands the app runs, as `app.clock.in`.
 97    var onAppCommand: ((String) -> Void)?
 98    /// Tags used across the workspace, for completion.
 99    var knownTags: @Sendable () -> [String] = { [] }
100
101    var theme: MobileTheme
102    internal(set) var fold = FoldState()
103    var globalVisibility: GlobalVisibility?
104    let hidden = LockedRanges()
105    /// Blocks drawn on a band.
106    let shaded = LockedRanges()
107    let fragmentStyle = FragmentStyle()
108    var selectionColor: UIColor = .clear
109    /// `org-indent-mode` and `org-hide-leading-stars`, from the settings and `#+STARTUP`.
110    var indented = true
111    var hideStars = false
112    /// One paragraph style per indent pair.
113    var paragraphStyles: [[Int]: NSParagraphStyle] = [:]
114    /// The line last revealed while markup is hidden, to hide again when the caret leaves.
115    var revealedLine: NSRange?
116    /// `org-toggle-inline-images`: lines that are only an image link show the image.
117    internal(set) var showsImages = false
118    /// `org-latex-preview`: LaTeX fragments show as typeset math.
119    internal(set) var showsLatex = false
120    /// The view width images were last sized for.
121    var imageWidth: CGFloat = 0
122    /// The file's folder, for relative image paths.
123    let baseDirectory: URL?
124    /// An `attachment:` link's file, from its name, offset and the tree; nil leaves those links
125    /// as text.
126    var attachmentPath: ((String, Int, OrgTree) -> String?)?
127    static let imageCache = NSCache<NSString, UIImage>()
128    var loading = false
129    var restyleScheduled: Range<Int>?
130    /// Narrowed table columns (`org-table-shrink`).
131    var shrunk = ShrunkColumns()
132    /// A command's edits being applied, which keep shrunk columns narrow.
133    private var commandEditing = false
134
135    init(
136        document: DocumentState, editable: Bool, options: EditingOptions = .org, theme spec: ThemeSpec = .default,
137        showMarkup: Bool = true, baseDirectory: URL? = nil
138    ) {
139        self.document = document
140        self.options = options
141        self.showMarkup = showMarkup
142        self.baseDirectory = baseDirectory
143        theme = MobileTheme(spec)
144        let keyed = KeyedTextView(usingTextLayoutManager: true)
145        textView = keyed
146        textViews = [keyed]
147        super.init()
148        configure(keyed, editable: editable)
149        textView.textStorage.delegate = self
150        (textView.textLayoutManager?.textContentManager as? NSTextContentStorage)?.delegate = self
151        let startup = Presentation.startupDisplay(document.tree, options: options)
152        indented = startup.indented
153        hideStars = startup.hideStars
154        showsImages = startup.inlineImages
155        showsLatex = startup.latexPreview
156        shrunk = ShrunkColumns.startup(document.tree)
157        applyThemeToView()
158        load(document.text)
159        setFolds(startup.folds)
160        if startup.alignTables { _ = perform(AlignAllTables()) }
161        truncatesLines = startup.truncated
162        textView.selectedRange = NSRange(location: 0, length: 0)
163    }
164
165    /// What every view of the buffer has: the keymap, the editor as its delegates and the fold
166    /// tap. Views in one scene share its undo stack.
167    private func configure(_ view: KeyedTextView, editable: Bool) {
168        view.keyHandler = { [weak self, weak view] key in
169            guard let self else { return false }
170            if let view { focus(view) }
171            return handleKey(key)
172        }
173        view.onLayout = { [weak self] in self?.viewResized() }
174        view.isEditable = editable
175        view.autocorrectionType = .no
176        view.autocapitalizationType = .none
177        view.smartQuotesType = .no
178        view.smartDashesType = .no
179        view.smartInsertDeleteType = .no
180        view.spellCheckingType = options.spellCheck ? .yes : .no
181        view.keyboardDismissMode = .interactive
182        view.alwaysBounceVertical = true
183        view.textContainerInset = UIEdgeInsets(top: 12, left: 8, bottom: 24, right: 8)
184        view.delegate = self
185        view.textLayoutManager?.delegate = self
186        let foldTap = UITapGestureRecognizer(target: self, action: #selector(tappedFold))
187        foldTap.delegate = self
188        view.addGestureRecognizer(foldTap)
189    }
190
191    // MARK: - Views
192
193    /// Another view of the buffer, for another pane: its own layout manager on the buffer's
194    /// content storage, so text, folds and styles are shared and the caret and scroll aren't.
195    func addView() -> UITextView {
196        guard let storage = textViews[0].textLayoutManager?.textContentManager as? NSTextContentStorage else { return textViews[0] }
197        let manager = NSTextLayoutManager()
198        manager.delegate = self
199        let container = NSTextContainer(size: CGSize(width: 0, height: CGFloat.greatestFiniteMagnitude))
200        manager.textContainer = container
201        storage.addTextLayoutManager(manager)
202        let view = KeyedTextView(frame: .zero, textContainer: container)
203        configure(view, editable: textViews[0].isEditable)
204        textViews.append(view)
205        applyThemeToView(view)
206        if truncatesLines { view.truncates = true }
207        updateCursor()
208        return view
209    }
210
211    /// Drops a view `addView` made; the first stays with the editor.
212    func removeView(_ view: UITextView) {
213        guard view !== textViews[0], let index = textViews.firstIndex(where: { $0 === view }) else { return }
214        textViews.remove(at: index)
215        if let manager = view.textLayoutManager, let storage = manager.textContentManager { storage.removeTextLayoutManager(manager) }
216        view.delegate = nil
217        onFocus[ObjectIdentifier(view)] = nil
218        if textView === view { textView = textViews[0] }
219    }
220
221    /// What each view's screen does when its view takes focus: the editor's callbacks are
222    /// that screen's from then on.
223    var onFocus: [ObjectIdentifier: () -> Void] = [:]
224
225    /// Commands act on `view` from now on.
226    func focus(_ view: UITextView) {
227        guard view !== textView, textViews.contains(where: { $0 === view }) else { return }
228        textView = view
229        onFocus[ObjectIdentifier(view)]?()
230    }
231
232    /// Every view's layout manager.
233    var layoutManagers: [NSTextLayoutManager] { textViews.compactMap(\.textLayoutManager) }
234
235    // MARK: - DocumentBuffer
236
237    var selection: [Range<Int>] {
238        let selected = textView.selectedRange
239        return [selected.location..<NSMaxRange(selected)]
240    }
241
242    func update<T>(_ change: (inout DocumentState) throws -> T) rethrows -> T {
243        let before = document.text
244        let defaultsBefore = document.defaults
245        let selected = textView.selectedRange
246        let result = try change(&document)
247        if document.text != before {
248            // A save that merged a change from disk, or a revert: the view shows the new text.
249            shrunk = ShrunkColumns()
250            load(document.text)
251            let length = (document.text as NSString).length
252            textView.selectedRange = NSRange(location: min(selected.location, length), length: 0)
253            textView.undoManager?.removeAllActions()
254            setFolds(fold)
255        } else if document.defaults != defaultsBefore {
256            restyle(0..<(document.text as NSString).length)
257        }
258        return result
259    }
260
261    func perform(_ command: any OrgCommand, now: Date = Date(), answers: [String: String] = [:]) -> CommandStep {
262        let context = EditContext(
263            revision: document.revision, text: document.text, tree: document.tree, selection: selection,
264            now: now, answers: answers, hidden: hidden.all, options: options, knownTags: knownTags
265        )
266        let step = command.run(in: context)
267        switch step {
268        case .commit(let result):
269            guard textView.isEditable || result.edits.isEmpty else {
270                onMessage?("This file is read-only.")
271                return .failed("read-only")
272            }
273            commandEditing = true
274            applyEdits(result.edits)
275            commandEditing = false
276            if let selected = result.selection?.first {
277                unfold(around: selected.lowerBound)
278                textView.selectedRange = NSRange(location: selected.lowerBound, length: selected.count)
279                textView.scrollRangeToVisible(textView.selectedRange)
280            }
281            for effect in result.effects {
282                switch effect {
283                case .message(let text): onMessage?(text)
284                case .fold(let start):
285                    var state = fold
286                    state.folds.insert(start)
287                    setFolds(state)
288                case .refreshSetup: onRefreshSetup?()
289                case .timer(let timer): TimerModel.shared.set(timer)
290                default: break
291                }
292            }
293        case .failed(let message):
294            onMessage?(message)
295        case .prompt(let prompt):
296            onPrompt?(prompt) { [weak self] answer in
297                guard let self else { return }
298                guard let answer else { return self.onMessage?("Quit") ?? () }
299                _ = self.perform(command, now: now, answers: answers.merging([prompt.key: answer]) { $1 })
300            }
301        case .external(.editBlock(let edit)) where onEditBlock != nil:
302            onEditBlock?(edit)
303        case .external(.babel(let job)) where onBabel != nil:
304            onBabel?(job)
305        case .external(.tangle(let scope)) where onTangle != nil:
306            onTangle?(scope)
307        case .external(.agenda(let start, let count)) where onAgenda != nil:
308            onAgenda?(start, count)
309        case .external(.columnView(let view)) where onColumnView != nil:
310            onColumnView?(view)
311        case .external(let request):
312            onMessage?(Self.unavailable(request, title: command.title))
313        }
314        return step
315    }
316
317    /// Why a request the app doesn't handle did nothing: only table recalculation needs Emacs.
318    static func unavailable(_ request: ExternalRequest, title: String) -> String {
319        if case .emacsTable(_, _, _, let reason, _) = request { return "This table needs Emacs, which runs on the Mac: \(reason)." }
320        return "\(title) isn't available on iPhone and iPad."
321    }
322
323    // MARK: - Commands by name and key
324
325    /// Runs what `keys` (as `C-c C-t`) is bound to in the Emacs keymap, for the caret's context.
326    func run(keys: String) {
327        guard let chords = KeySequence.parse(keys) else { return }
328        let context = editContext()
329        let binding = keymap.candidates(for: chords).first { binding in
330            (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
331        }
332        guard let binding else { return onMessage?("Nothing to do here") ?? () }
333        run(binding.command)
334    }
335
336    func run(_ id: String) {
337        switch id {
338        case "org.cycle":
339            if !cycleAtCaret() { onMessage?("Not on a heading, drawer or block") }
340        case "org.cycle-global": cycleGlobal()
341        case "org.link.open": openLinkAtCaret()
342        case "org.toggle-inline-images": toggleImages()
343        case "org.latex-preview": toggleLatex()
344        case "editor.toggle-truncate-lines":
345            truncatesLines.toggle()
346            onMessage?(truncatesLines ? "Truncate long lines enabled" : "Truncate long lines disabled")
347        case "edit.isearch-forward": startISearch(forward: true)
348        case "edit.isearch-backward": startISearch(forward: false)
349        case "edit.isearch-forward-regexp": startISearch(forward: true, regexp: true)
350        case "edit.isearch-backward-regexp": startISearch(forward: false, regexp: true)
351        case "editor.toggle-auto-fill":
352            autoFillOverride = !autoFills
353            onMessage?(autoFills ? "Auto-Fill mode enabled in current buffer" : "Auto-Fill mode disabled in current buffer")
354        case "edit.undo": textView.undoManager?.undo()
355        case "edit.redo": textView.undoManager?.redo()
356        case "org.table.toggle-column-width", "org.table.shrink", "org.table.expand": tableColumnWidth(id)
357        case _ where id.hasPrefix("app.") || Self.linkCommands.contains(id):
358            if let onAppCommand { onAppCommand(id) } else { onMessage?("Not available on iOS yet") }
359        default:
360            if let command = Commands.command(id) {
361                _ = perform(command)
362            } else {
363                onMessage?("Not available on iOS yet")
364            }
365        }
366    }
367
368    /// Link commands that need the stored links or the file, which the screen has.
369    static let linkCommands: Set<String> = ["org.link.store", "org.id.store-link", "org.link.insert"]
370
371    func applies(_ id: String, in context: EditContext) -> Bool {
372        if let command = Commands.command(id) { return command.applies(in: context) }
373        switch id {
374        case "org.cycle":
375            return Presentation.heading(containing: context.caret, in: context.tree) != nil || Wrappers.toggleable(at: context.caret, in: context.tree) != nil
376        case "org.cycle-global", "edit.undo", "edit.redo", "org.toggle-inline-images", "org.latex-preview", "editor.toggle-truncate-lines",
377             "editor.toggle-auto-fill", "edit.isearch-forward", "edit.isearch-backward",
378             "edit.isearch-forward-regexp", "edit.isearch-backward-regexp": return true
379        case "app.clock.in", "app.clock.out", "app.clock.cancel", "app.clock.goto", "app.clock.in-recent", "app.clock.in-last",
380             "app.clock.goto-recent", "app.clock.default", "app.clock.resolve", "app.toggle-markup": return onAppCommand != nil
381        case "app.refile.goto", "app.table-import", "app.crypt.encrypt-entries", "app.crypt.forget-passphrase", "app.attach.attach", "app.attach.url",
382             "app.attach.new", "app.attach.open", "app.attach.reveal", "app.attach.delete", "app.attach.delete-all", "app.attach.sync",
383             "app.attach.set-directory", "app.attach.unset-directory", "app.backlinks", "app.node.find", "app.node.insert": return onAppCommand != nil
384        case _ where id.hasPrefix("app.dailies."): return onAppCommand != nil
385        case "app.crypt.encrypt-entry": return onAppCommand != nil && OrgCrypt.heading(context.text, at: context.caret) != nil && OrgCrypt.encryptedRange(context.text, at: context.caret) == nil
386        case "app.crypt.open-entry", "app.crypt.decrypt-entry": return onAppCommand != nil && OrgCrypt.encryptedRange(context.text, at: context.caret) != nil
387        case "app.table-export", "app.plot": return onAppCommand != nil && ImportTable.exportText(context.text, at: context.caret, path: "") != nil
388        case "app.refile", "app.refile.copy": return onAppCommand != nil && Presentation.heading(containing: context.caret, in: context.tree) != nil
389        case _ where Self.linkCommands.contains(id): return onAppCommand != nil
390        case "org.link.open": return OpenLinkAtPoint().applies(in: context)
391        case "org.table.toggle-column-width", "org.table.shrink", "org.table.expand":
392            return TableShrink.table(at: context.caret, in: context.text) != nil
393        default: return false
394        }
395    }
396
397    // MARK: - Hardware keyboard
398
399    lazy var dispatcher = KeyDispatcher(keymap: keymap)
400
401    private static let named: [UIKeyboardHIDUsage: String] = [
402        .keyboardTab: "TAB", .keyboardReturnOrEnter: "RET", .keypadEnter: "RET", .keyboardSpacebar: "SPC",
403        .keyboardEscape: "ESC", .keyboardDeleteOrBackspace: "DEL", .keyboardDeleteForward: "<delete>",
404        .keyboardLeftArrow: "<left>", .keyboardRightArrow: "<right>", .keyboardUpArrow: "<up>", .keyboardDownArrow: "<down>",
405        .keyboardHome: "<home>", .keyboardEnd: "<end>", .keyboardPageUp: "<prior>", .keyboardPageDown: "<next>",
406    ]
407
408    /// A key press as a chord; Option is Meta, as `option-as-meta` makes it on the Mac.
409    static func chord(_ key: UIKey) -> KeyChord? {
410        var modifiers: KeyChord.Modifiers = []
411        let flags = key.modifierFlags
412        if flags.contains(.control) { modifiers.insert(.control) }
413        if flags.contains(.alternate) { modifiers.insert(.meta) }
414        if flags.contains(.command) { modifiers.insert(.command) }
415        if let name = named[key.keyCode] {
416            if flags.contains(.shift) { modifiers.insert(.shift) }
417            return KeyChord(name, modifiers)
418        }
419        var characters = key.charactersIgnoringModifiers
420        if flags.contains(.shift), characters.count == 1, characters.lowercased() == characters { characters = characters.uppercased() }
421        guard characters.count == 1 else { return nil }
422        return KeyChord(characters, modifiers)
423    }
424
425    /// The Emacs keymap's commands on an iPad keyboard. Keys it doesn't bind, Command shortcuts
426    /// and editing keys (C-a, C-e, C-k...) are the text system's.
427    func handleKey(_ key: UIKey) -> Bool {
428        guard let chord = Self.chord(key), !chord.modifiers.contains(.command) else { return false }
429        if isearch != nil, isearchKey(chord) { return true }
430        if modal { return handleModal(chord) }
431        // Option alone types characters unless it begins a binding.
432        if chord.modifiers == [.meta], dispatcher.pending.isEmpty,
433           keymap.candidates(for: [chord]).isEmpty, !keymap.isPrefix([chord]) { return false }
434        switch dispatcher.feed(chord) {
435        case .pending(let keys):
436            onMessage?(KeySequence.format(keys) + "-")
437            return true
438        case .cancelled:
439            onMessage?("Quit")
440            return true
441        case .undefined(let keys):
442            onMessage?("\(KeySequence.format(keys)) is undefined")
443            return true
444        case .unbound:
445            return false
446        case .complete(let keys, let candidates):
447            let context = editContext()
448            let runnable = candidates.first { binding in
449                (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
450            }
451            // A sequence runs its command even where it doesn't apply, which says why, as on the Mac.
452            guard let binding = runnable ?? (keys.count > 1 ? candidates.first : nil) else { return false }
453            if keys.count == 1, binding.command.hasPrefix("edit."), !["edit.undo", "edit.redo"].contains(binding.command) { return false }
454            run(binding.command)
455            return true
456        }
457    }
458
459    func editContext() -> EditContext {
460        EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: selection, hidden: hidden.all, options: options, knownTags: knownTags)
461    }
462
463    private func openLinkAtCaret() {
464        let caret = textView.selectedRange.location
465        if let link = Links.link(at: caret, text: document.text, tree: document.tree)?.link {
466            onLink?(link)
467        } else if let days = Links.timestampDays(at: caret, text: document.text) {
468            onAgenda?(days.start, days.count)
469        } else {
470            onMessage?("No link here")
471        }
472    }
473
474    // MARK: - Editing
475
476    /// Applies `edits` (against the current text) through the text view as one undo step.
477    func applyEdits(_ edits: [TextEdit]) {
478        let interval = Perf.begin("editor.applyEdits")
479        defer { interval.end() }
480        guard !edits.isEmpty else { return }
481        applyingEdits = true
482        defer { applyingEdits = false }
483        // Straight into the storage: replacing through text input would take the active
484        // keyboard's substitutions (smart dashes) when another view has the keyboard.
485        let storage = textView.textStorage
486        let old = storage.string as NSString
487        // By lines, so a fold between two changes stays.
488        let ascending = edits.flatMap { splitByLines($0, in: storage.string) }.sorted { $0.range.lowerBound < $1.range.lowerBound }
489        var inverse: [TextEdit] = []
490        var delta = 0
491        for edit in ascending {
492            let start = edit.range.lowerBound + delta
493            let length = (edit.replacement as NSString).length
494            inverse.append(TextEdit(range: start..<start + length, replacement: old.substring(with: NSRange(edit.range))))
495            delta += length - edit.range.count
496        }
497        let caret = textView.selectedRange
498        // One at a time, last first: each is processed alone, so folds between them stay.
499        for edit in ascending.reversed() {
500            storage.replaceCharacters(in: NSRange(edit.range), with: edit.replacement)
501        }
502        textView.undoManager?.registerUndo(withTarget: self) { editor in
503            editor.applyEdits(inverse)
504            editor.textView.selectedRange = caret
505        }
506    }
507
508    /// The storage changed (typing, a command, undo): the document takes the same edit, and
509    /// folds and styles follow.
510    fileprivate func storageEdited(range: NSRange, delta: Int) {
511        let interval = Perf.begin("editor.edit")
512        defer { interval.end() }
513        guard !loading else { return }
514        let old = range.location..<(range.location + range.length - delta)
515        let replacement = (textView.textStorage.string as NSString).substring(with: range)
516        let edit = TextEdit(range: old, replacement: replacement)
517        do {
518            try document.apply([edit], baseRevision: document.revision)
519        } catch {
520            // Out of step: the view's text wins.
521            shrunk = ShrunkColumns()
522            load(textView.textStorage.string)
523            return
524        }
525        for table in shrunk.map(through: edit, in: textView.textStorage.string, command: commandEditing) { scheduleRestyle(table) }
526        fold = FoldState(
527            folds: Self.map(fold.folds, old, delta), bodyFolds: Self.map(fold.bodyFolds, old, delta),
528            wrapperFolds: Self.map(fold.wrapperFolds, old, delta)
529        )
530        scheduleRestyle(range.location..<NSMaxRange(range))
531        onChange?()
532    }
533
534    /// Starts after the edit move with it; ones inside it go.
535    static func map(_ starts: Set<Int>, _ old: Range<Int>, _ delta: Int) -> Set<Int> {
536        Set(starts.compactMap { start in
537            if start >= old.upperBound { return start + delta }
538            return start <= old.lowerBound ? start : nil
539        })
540    }
541
542}
543
544extension MobileEditor: UITextViewDelegate {
545    func textViewDidBeginEditing(_ textView: UITextView) {
546        focus(textView)
547    }
548
549    /// Another view's caret moves with edits made in this one; only the focused view's
550    /// selection drives the display.
551    func textViewDidChangeSelection(_ textView: UITextView) {
552        if textView.isFirstResponder { focus(textView) }
553        guard textView === self.textView else { return }
554        selectionChanged()
555    }
556
557    /// `electric-pair-mode` for typed brackets and quotes, DEL and RET, and `auto-fill-mode`
558    /// for a typed space, from either keyboard.
559    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
560        if isearch != nil, !applyingEdits {
561            isearchTyped(text)
562            return false
563        }
564        if !applyingEdits { typedOutsideInsert() }
565        if autoFills, !applyingEdits, textView.markedTextRange == nil, text == " ", range == textView.selectedRange {
566            _ = perform(AutoFillSpace())
567            return false
568        }
569        guard options.electricPair, !applyingEdits, textView.markedTextRange == nil else { return true }
570        let selected = textView.selectedRange
571        let key: String
572        if text.isEmpty, selected.length == 0, range.length == 1, NSMaxRange(range) == selected.location {
573            key = "DEL"
574        } else if range == selected, text == "\n" {
575            key = "RET"
576        } else if range == selected, ElectricPairKey.characters.contains(text) {
577            key = text
578        } else {
579            return true
580        }
581        let command = ElectricPairKey(key: key)
582        guard command.applies(in: editContext()) else { return true }
583        _ = perform(command)
584        return false
585    }
586}
587
588extension MobileEditor: UIGestureRecognizerDelegate {
589    /// The drawer or block a tap at `point` folds or unfolds: a folded one's `…`, the space after
590    /// its first line, or anywhere on an open drawer's first line.
591    private func foldToggle(at point: CGPoint, in view: UITextView? = nil) -> Int? {
592        let textView = view ?? textView
593        guard let manager = textView.textLayoutManager, let content = manager.textContentManager else { return nil }
594        let inContainer = CGPoint(x: point.x - textView.textContainerInset.left, y: point.y - textView.textContainerInset.top)
595        guard let fragment = manager.textLayoutFragment(for: inContainer), let range = fragment.textElement?.elementRange else { return nil }
596        let start = content.offset(from: content.documentRange.location, to: range.location)
597        guard let line = fragment.textLineFragments.first(where: { $0.characterRange.length > 0 }) ?? fragment.textLineFragments.first else { return nil }
598        if hidden.isFolded(start) { return inContainer.x - fragment.layoutFragmentFrame.minX >= line.typographicBounds.maxX ? start : nil }
599        guard Wrappers.starting(at: start, in: document.tree)?.kind == .drawer,
600              inContainer.y - fragment.layoutFragmentFrame.minY < line.typographicBounds.maxY else { return nil }
601        return start
602    }
603
604    /// A tap on a fold's `…` opens it, and one on an open drawer's first line folds it, as TAB
605    /// on the line does.
606    @objc fileprivate func tappedFold(_ tap: UITapGestureRecognizer) {
607        if let view = tap.view as? UITextView { focus(view) }
608        guard let start = foldToggle(at: tap.location(in: textView)),
609              let next = Presentation.cycle(at: start, in: document.tree, fold) else { return }
610        setFolds(next)
611    }
612
613    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
614        guard let view = gestureRecognizer.view as? UITextView else { return false }
615        return foldToggle(at: gestureRecognizer.location(in: view), in: view) != nil
616    }
617
618    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer) -> Bool {
619        true
620    }
621}
622
623extension MobileEditor: NSTextStorageDelegate {
624    nonisolated func textStorage(
625        _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorage.EditActions, range editedRange: NSRange, changeInLength delta: Int
626    ) {
627        guard editedMask.contains(.editedCharacters) else { return }
628        MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
629    }
630}
631
632extension MobileEditor: NSTextContentStorageDelegate {
633    /// Folded text isn't enumerated, so it isn't laid out or drawn.
634    nonisolated func textContentManager(
635        _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
636    ) -> Bool {
637        guard let range = textElement.elementRange else { return true }
638        let documentStart = textContentManager.documentRange.location
639        let start = textContentManager.offset(from: documentStart, to: range.location)
640        let end = textContentManager.offset(from: documentStart, to: range.endLocation)
641        return !hidden.covers(start, end)
642    }
643}
644
645extension MobileEditor: NSTextLayoutManagerDelegate {
646    /// Folded headings, drawers and blocks end with `…`; blocks are on a band; image lines
647    /// show their image; pretty entities draw their character.
648    nonisolated func textLayoutManager(
649        _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
650    ) -> NSTextLayoutFragment {
651        let range = textElement.elementRange
652        guard let range, let manager = textLayoutManager.textContentManager else { return NSTextLayoutFragment(textElement: textElement, range: range) }
653        let offset = manager.offset(from: manager.documentRange.location, to: range.location)
654        let folded = hidden.isFolded(offset)
655        let band = shaded.containing(offset) != nil ? fragmentStyle.blockBand : nil
656        let string = (textElement as? NSTextParagraph)?.attributedString
657        let image = string.flatMap(OrgLineFragment.image)
658        let entities = string.map(OrgLineFragment.hasEntities) ?? false
659        let latex = string.map(OrgLineFragment.hasLatex) ?? false
660        guard folded || band != nil || image != nil || entities || latex else { return NSTextLayoutFragment(textElement: textElement, range: range) }
661        let fragment = OrgLineFragment(textElement: textElement, range: range)
662        fragment.folded = folded
663        fragment.band = band
664        if band != nil {
665            fragment.start = offset
666            fragment.style = fragmentStyle
667        }
668        fragment.image = image
669        return fragment
670    }
671}
672#endif