Sources/OrgstarMobile/MobileEditor.swift

d85099bc95bf1766aee990d94671dacda0c0686e
orgstar/Sources/OrgstarMobile/MobileEditor.swift history · blame · raw

563 lines · 27033 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    let textView: UITextView
 19    var options: EditingOptions = .org {
 20        didSet {
 21            textView.spellCheckingType = options.spellCheck ? .yes : .no
 22            if !showMarkup, options.hideEmphasisMarkers != oldValue.hideEmphasisMarkers || options.prettyEntities != oldValue.prettyEntities {
 23                restyleAll()
 24            }
 25        }
 26    }
 27    /// Colors and type; a change, or a new Dynamic Type size, restyles the file.
 28    var themeSpec: ThemeSpec {
 29        get { theme.spec }
 30        set {
 31            let new = MobileTheme(newValue)
 32            guard new.spec != theme.spec || new.font != theme.font else { return }
 33            theme = new
 34            paragraphStyles = [:]
 35            applyThemeToView()
 36            restyleAll()
 37        }
 38    }
 39    /// Link brackets and targets, and emphasis markers when `org-hide-emphasis-markers` hides
 40    /// them, shown. Hidden markup shows on the caret's line, so it can be edited.
 41    var showMarkup = true {
 42        didSet { if showMarkup != oldValue { restyleAll() } }
 43    }
 44    var keymap = KeymapPreset.emacs.keymap {
 45        didSet { dispatcher = KeyDispatcher(keymap: keymap) }
 46    }
 47    /// The Doom preset's modal editing, and its state: the engine, the caret in visual
 48    /// states, marks, the jump list, what insert state began with, and macros.
 49    var modal = false {
 50        didSet {
 51            if modal != oldValue { vim = Vim() }
 52            updateCursor()
 53        }
 54    }
 55    var vim = Vim()
 56    var visualCaret: Int?
 57    var vimMarks: [Character: Int] = [:]
 58    var jumpList: [Int] = []
 59    var jumpIndex = 0
 60    var insertSnapshot: String?
 61    var recordingRegister: Character?
 62    var recordedKeys: [KeyChord] = []
 63    var replayingMacro = 0
 64    static var vimRegisters: [Character: (text: String, linewise: Bool)] = [:]
 65    static var vimClipboardRecord: (text: String, linewise: Bool)?
 66    static var macros: [Character: [KeyChord]] = [:]
 67    /// What `:`, `/` and `?` read, oldest first, for `q:`.
 68    static var promptHistory: [String: [String]] = [:]
 69    var onChange: (() -> Void)?
 70    var onMessage: ((String) -> Void)?
 71    var onPrompt: ((Prompt, @escaping (String?) -> Void) -> Void)?
 72    var onLink: ((OrgLink) -> Void)?
 73    /// Edits being applied, which the typing hooks leave alone.
 74    private var applyingEdits = false
 75    /// Source blocks to write to their files (C-c C-v t).
 76    var onTangle: ((Tangle.Scope) -> Void)?
 77    /// A source block to run (C-c C-c).
 78    var onBabel: ((BabelJob) -> Void)?
 79    /// The file's setup files to read again (C-c C-c on a keyword line).
 80    var onRefreshSetup: (() -> Void)?
 81    /// A block, a table's formulas or a field to edit apart (C-c ', C-c `).
 82    var onEditBlock: ((BlockEdit) -> Void)?
 83    /// A followed timestamp's agenda days: the first (a `Days` number) and how many.
 84    var onAgenda: ((Int, Int) -> Void)?
 85    /// Shows a column view.
 86    var onColumnView: ((ColumnView.View) -> Void)?
 87    /// Commands the app runs, as `app.clock.in`.
 88    var onAppCommand: ((String) -> Void)?
 89    /// Tags used across the workspace, for completion.
 90    var knownTags: @Sendable () -> [String] = { [] }
 91
 92    var theme: MobileTheme
 93    internal(set) var fold = FoldState()
 94    var globalVisibility: GlobalVisibility?
 95    let hidden = LockedRanges()
 96    /// Blocks drawn on a band.
 97    let shaded = LockedRanges()
 98    let fragmentStyle = FragmentStyle()
 99    var selectionColor: UIColor = .clear
100    /// `org-indent-mode` and `org-hide-leading-stars`, from the settings and `#+STARTUP`.
101    var indented = true
102    var hideStars = false
103    /// One paragraph style per indent pair.
104    var paragraphStyles: [[Int]: NSParagraphStyle] = [:]
105    /// The line last revealed while markup is hidden, to hide again when the caret leaves.
106    var revealedLine: NSRange?
107    /// `org-toggle-inline-images`: lines that are only an image link show the image.
108    internal(set) var showsImages = false
109    /// The view width images were last sized for.
110    var imageWidth: CGFloat = 0
111    /// The file's folder, for relative image paths.
112    let baseDirectory: URL?
113    static let imageCache = NSCache<NSString, UIImage>()
114    var loading = false
115    var restyleScheduled: Range<Int>?
116    /// Narrowed table columns (`org-table-shrink`).
117    var shrunk = ShrunkColumns()
118    /// A command's edits being applied, which keep shrunk columns narrow.
119    private var commandEditing = false
120
121    init(
122        document: DocumentState, editable: Bool, options: EditingOptions = .org, theme spec: ThemeSpec = .default,
123        showMarkup: Bool = true, baseDirectory: URL? = nil
124    ) {
125        self.document = document
126        self.options = options
127        self.showMarkup = showMarkup
128        self.baseDirectory = baseDirectory
129        theme = MobileTheme(spec)
130        let keyed = KeyedTextView(usingTextLayoutManager: true)
131        textView = keyed
132        super.init()
133        keyed.keyHandler = { [weak self] key in self?.handleKey(key) ?? false }
134        keyed.onLayout = { [weak self] in self?.viewResized() }
135        textView.isEditable = editable
136        textView.autocorrectionType = .no
137        textView.autocapitalizationType = .none
138        textView.smartQuotesType = .no
139        textView.smartDashesType = .no
140        textView.smartInsertDeleteType = .no
141        textView.spellCheckingType = options.spellCheck ? .yes : .no
142        textView.keyboardDismissMode = .interactive
143        textView.alwaysBounceVertical = true
144        textView.textContainerInset = UIEdgeInsets(top: 12, left: 8, bottom: 24, right: 8)
145        textView.delegate = self
146        textView.textStorage.delegate = self
147        textView.textLayoutManager?.delegate = self
148        (textView.textLayoutManager?.textContentManager as? NSTextContentStorage)?.delegate = self
149        let foldTap = UITapGestureRecognizer(target: self, action: #selector(tappedFold))
150        foldTap.delegate = self
151        textView.addGestureRecognizer(foldTap)
152        let startup = Presentation.startupDisplay(document.tree, options: options)
153        indented = startup.indented
154        hideStars = startup.hideStars
155        showsImages = startup.inlineImages
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    // MARK: - DocumentBuffer
166
167    var selection: [Range<Int>] {
168        let selected = textView.selectedRange
169        return [selected.location..<NSMaxRange(selected)]
170    }
171
172    func update<T>(_ change: (inout DocumentState) throws -> T) rethrows -> T {
173        let before = document.text
174        let defaultsBefore = document.defaults
175        let selected = textView.selectedRange
176        let result = try change(&document)
177        if document.text != before {
178            // A save that merged a change from disk, or a revert: the view shows the new text.
179            shrunk = ShrunkColumns()
180            load(document.text)
181            let length = (document.text as NSString).length
182            textView.selectedRange = NSRange(location: min(selected.location, length), length: 0)
183            textView.undoManager?.removeAllActions()
184            setFolds(fold)
185        } else if document.defaults != defaultsBefore {
186            restyle(0..<(document.text as NSString).length)
187        }
188        return result
189    }
190
191    func perform(_ command: any OrgCommand, now: Date = Date(), answers: [String: String] = [:]) -> CommandStep {
192        let context = EditContext(
193            revision: document.revision, text: document.text, tree: document.tree, selection: selection,
194            now: now, answers: answers, hidden: hidden.all, options: options, knownTags: knownTags
195        )
196        let step = command.run(in: context)
197        switch step {
198        case .commit(let result):
199            guard textView.isEditable || result.edits.isEmpty else {
200                onMessage?("This file is read-only.")
201                return .failed("read-only")
202            }
203            commandEditing = true
204            applyEdits(result.edits)
205            commandEditing = false
206            if let selected = result.selection?.first {
207                unfold(around: selected.lowerBound)
208                textView.selectedRange = NSRange(location: selected.lowerBound, length: selected.count)
209                textView.scrollRangeToVisible(textView.selectedRange)
210            }
211            for effect in result.effects {
212                switch effect {
213                case .message(let text): onMessage?(text)
214                case .fold(let start):
215                    var state = fold
216                    state.folds.insert(start)
217                    setFolds(state)
218                case .refreshSetup: onRefreshSetup?()
219                default: break
220                }
221            }
222        case .failed(let message):
223            onMessage?(message)
224        case .prompt(let prompt):
225            onPrompt?(prompt) { [weak self] answer in
226                guard let self else { return }
227                guard let answer else { return self.onMessage?("Quit") ?? () }
228                _ = self.perform(command, now: now, answers: answers.merging([prompt.key: answer]) { $1 })
229            }
230        case .external(.editBlock(let edit)) where onEditBlock != nil:
231            onEditBlock?(edit)
232        case .external(.babel(let job)) where onBabel != nil:
233            onBabel?(job)
234        case .external(.tangle(let scope)) where onTangle != nil:
235            onTangle?(scope)
236        case .external(.agenda(let start, let count)) where onAgenda != nil:
237            onAgenda?(start, count)
238        case .external(.columnView(let view)) where onColumnView != nil:
239            onColumnView?(view)
240        case .external(let request):
241            onMessage?(Self.unavailable(request, title: command.title))
242        }
243        return step
244    }
245
246    /// Why a request the app doesn't handle did nothing: only table recalculation needs Emacs.
247    static func unavailable(_ request: ExternalRequest, title: String) -> String {
248        if case .emacsTable(_, _, _, let reason, _) = request { return "This table needs Emacs, which runs on the Mac: \(reason)." }
249        return "\(title) isn't available on iPhone and iPad."
250    }
251
252    // MARK: - Commands by name and key
253
254    /// Runs what `keys` (as `C-c C-t`) is bound to in the Emacs keymap, for the caret's context.
255    func run(keys: String) {
256        guard let chords = KeySequence.parse(keys) else { return }
257        let context = editContext()
258        let binding = keymap.candidates(for: chords).first { binding in
259            (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
260        }
261        guard let binding else { return onMessage?("Nothing to do here") ?? () }
262        run(binding.command)
263    }
264
265    func run(_ id: String) {
266        switch id {
267        case "org.cycle":
268            if !cycleAtCaret() { onMessage?("Not on a heading, drawer or block") }
269        case "org.cycle-global": cycleGlobal()
270        case "org.link.open": openLinkAtCaret()
271        case "org.toggle-inline-images": toggleImages()
272        case "editor.toggle-truncate-lines":
273            truncatesLines.toggle()
274            onMessage?(truncatesLines ? "Truncate long lines enabled" : "Truncate long lines disabled")
275        case "edit.undo": textView.undoManager?.undo()
276        case "edit.redo": textView.undoManager?.redo()
277        case "org.table.toggle-column-width", "org.table.shrink", "org.table.expand": tableColumnWidth(id)
278        case _ where id.hasPrefix("app.") || Self.linkCommands.contains(id):
279            if let onAppCommand { onAppCommand(id) } else { onMessage?("Not available on iOS yet") }
280        default:
281            if let command = Commands.command(id) {
282                _ = perform(command)
283            } else {
284                onMessage?("Not available on iOS yet")
285            }
286        }
287    }
288
289    /// Link commands that need the stored links or the file, which the screen has.
290    static let linkCommands: Set<String> = ["org.link.store", "org.id.store-link", "org.link.insert"]
291
292    func applies(_ id: String, in context: EditContext) -> Bool {
293        if let command = Commands.command(id) { return command.applies(in: context) }
294        switch id {
295        case "org.cycle":
296            return Presentation.heading(containing: context.caret, in: context.tree) != nil || Wrappers.toggleable(at: context.caret, in: context.tree) != nil
297        case "org.cycle-global", "edit.undo", "edit.redo", "org.toggle-inline-images", "editor.toggle-truncate-lines": return true
298        case "app.clock.in", "app.clock.out", "app.clock.cancel", "app.clock.goto", "app.clock.in-recent", "app.clock.in-last",
299             "app.clock.goto-recent", "app.clock.default", "app.clock.resolve", "app.toggle-markup": return onAppCommand != nil
300        case "app.refile.goto": return onAppCommand != nil
301        case "app.refile", "app.refile.copy": return onAppCommand != nil && Presentation.heading(containing: context.caret, in: context.tree) != nil
302        case _ where Self.linkCommands.contains(id): return onAppCommand != nil
303        case "org.link.open": return OpenLinkAtPoint().applies(in: context)
304        case "org.table.toggle-column-width", "org.table.shrink", "org.table.expand":
305            return TableShrink.table(at: context.caret, in: context.text) != nil
306        default: return false
307        }
308    }
309
310    // MARK: - Hardware keyboard
311
312    lazy var dispatcher = KeyDispatcher(keymap: keymap)
313
314    private static let named: [UIKeyboardHIDUsage: String] = [
315        .keyboardTab: "TAB", .keyboardReturnOrEnter: "RET", .keypadEnter: "RET", .keyboardSpacebar: "SPC",
316        .keyboardEscape: "ESC", .keyboardDeleteOrBackspace: "DEL", .keyboardDeleteForward: "<delete>",
317        .keyboardLeftArrow: "<left>", .keyboardRightArrow: "<right>", .keyboardUpArrow: "<up>", .keyboardDownArrow: "<down>",
318        .keyboardHome: "<home>", .keyboardEnd: "<end>", .keyboardPageUp: "<prior>", .keyboardPageDown: "<next>",
319    ]
320
321    /// A key press as a chord; Option is Meta, as `option-as-meta` makes it on the Mac.
322    static func chord(_ key: UIKey) -> KeyChord? {
323        var modifiers: KeyChord.Modifiers = []
324        let flags = key.modifierFlags
325        if flags.contains(.control) { modifiers.insert(.control) }
326        if flags.contains(.alternate) { modifiers.insert(.meta) }
327        if flags.contains(.command) { modifiers.insert(.command) }
328        if let name = named[key.keyCode] {
329            if flags.contains(.shift) { modifiers.insert(.shift) }
330            return KeyChord(name, modifiers)
331        }
332        var characters = key.charactersIgnoringModifiers
333        if flags.contains(.shift), characters.count == 1, characters.lowercased() == characters { characters = characters.uppercased() }
334        guard characters.count == 1 else { return nil }
335        return KeyChord(characters, modifiers)
336    }
337
338    /// The Emacs keymap's commands on an iPad keyboard. Keys it doesn't bind, Command shortcuts
339    /// and editing keys (C-a, C-e, C-k...) are the text system's.
340    func handleKey(_ key: UIKey) -> Bool {
341        guard let chord = Self.chord(key), !chord.modifiers.contains(.command) else { return false }
342        if modal { return handleModal(chord) }
343        // Option alone types characters unless it begins a binding.
344        if chord.modifiers == [.meta], dispatcher.pending.isEmpty,
345           keymap.candidates(for: [chord]).isEmpty, !keymap.isPrefix([chord]) { return false }
346        switch dispatcher.feed(chord) {
347        case .pending(let keys):
348            onMessage?(KeySequence.format(keys) + "-")
349            return true
350        case .cancelled:
351            onMessage?("Quit")
352            return true
353        case .undefined(let keys):
354            onMessage?("\(KeySequence.format(keys)) is undefined")
355            return true
356        case .unbound:
357            return false
358        case .complete(let keys, let candidates):
359            let context = editContext()
360            let runnable = candidates.first { binding in
361                (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
362            }
363            // A sequence runs its command even where it doesn't apply, which says why, as on the Mac.
364            guard let binding = runnable ?? (keys.count > 1 ? candidates.first : nil) else { return false }
365            if keys.count == 1, binding.command.hasPrefix("edit."), !["edit.undo", "edit.redo"].contains(binding.command) { return false }
366            run(binding.command)
367            return true
368        }
369    }
370
371    func editContext() -> EditContext {
372        EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: selection, hidden: hidden.all, options: options, knownTags: knownTags)
373    }
374
375    private func openLinkAtCaret() {
376        let caret = textView.selectedRange.location
377        if let link = Links.link(at: caret, text: document.text, tree: document.tree)?.link {
378            onLink?(link)
379        } else if let days = Links.timestampDays(at: caret, text: document.text) {
380            onAgenda?(days.start, days.count)
381        } else {
382            onMessage?("No link here")
383        }
384    }
385
386    // MARK: - Editing
387
388    /// Applies `edits` (against the current text) through the text view as one undo step.
389    func applyEdits(_ edits: [TextEdit]) {
390        let interval = Perf.begin("editor.applyEdits")
391        defer { interval.end() }
392        guard !edits.isEmpty else { return }
393        applyingEdits = true
394        defer { applyingEdits = false }
395        // Straight into the storage: replacing through text input would take the active
396        // keyboard's substitutions (smart dashes) when another view has the keyboard.
397        let storage = textView.textStorage
398        let old = storage.string as NSString
399        // By lines, so a fold between two changes stays.
400        let ascending = edits.flatMap { splitByLines($0, in: storage.string) }.sorted { $0.range.lowerBound < $1.range.lowerBound }
401        var inverse: [TextEdit] = []
402        var delta = 0
403        for edit in ascending {
404            let start = edit.range.lowerBound + delta
405            let length = (edit.replacement as NSString).length
406            inverse.append(TextEdit(range: start..<start + length, replacement: old.substring(with: NSRange(edit.range))))
407            delta += length - edit.range.count
408        }
409        let caret = textView.selectedRange
410        // One at a time, last first: each is processed alone, so folds between them stay.
411        for edit in ascending.reversed() {
412            storage.replaceCharacters(in: NSRange(edit.range), with: edit.replacement)
413        }
414        textView.undoManager?.registerUndo(withTarget: self) { editor in
415            editor.applyEdits(inverse)
416            editor.textView.selectedRange = caret
417        }
418    }
419
420    /// The storage changed (typing, a command, undo): the document takes the same edit, and
421    /// folds and styles follow.
422    fileprivate func storageEdited(range: NSRange, delta: Int) {
423        let interval = Perf.begin("editor.edit")
424        defer { interval.end() }
425        guard !loading else { return }
426        let old = range.location..<(range.location + range.length - delta)
427        let replacement = (textView.textStorage.string as NSString).substring(with: range)
428        let edit = TextEdit(range: old, replacement: replacement)
429        do {
430            try document.apply([edit], baseRevision: document.revision)
431        } catch {
432            // Out of step: the view's text wins.
433            shrunk = ShrunkColumns()
434            load(textView.textStorage.string)
435            return
436        }
437        for table in shrunk.map(through: edit, in: textView.textStorage.string, command: commandEditing) { scheduleRestyle(table) }
438        fold = FoldState(
439            folds: Self.map(fold.folds, old, delta), bodyFolds: Self.map(fold.bodyFolds, old, delta),
440            wrapperFolds: Self.map(fold.wrapperFolds, old, delta)
441        )
442        scheduleRestyle(range.location..<NSMaxRange(range))
443        onChange?()
444    }
445
446    /// Starts after the edit move with it; ones inside it go.
447    static func map(_ starts: Set<Int>, _ old: Range<Int>, _ delta: Int) -> Set<Int> {
448        Set(starts.compactMap { start in
449            if start >= old.upperBound { return start + delta }
450            return start <= old.lowerBound ? start : nil
451        })
452    }
453
454}
455
456extension MobileEditor: UITextViewDelegate {
457    func textViewDidChangeSelection(_ textView: UITextView) {
458        selectionChanged()
459    }
460
461    /// `electric-pair-mode` for typed brackets and quotes, DEL and RET, from either keyboard.
462    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
463        if !applyingEdits { typedOutsideInsert() }
464        guard options.electricPair, !applyingEdits, textView.markedTextRange == nil else { return true }
465        let selected = textView.selectedRange
466        let key: String
467        if text.isEmpty, selected.length == 0, range.length == 1, NSMaxRange(range) == selected.location {
468            key = "DEL"
469        } else if range == selected, text == "\n" {
470            key = "RET"
471        } else if range == selected, ElectricPairKey.characters.contains(text) {
472            key = text
473        } else {
474            return true
475        }
476        let command = ElectricPairKey(key: key)
477        guard command.applies(in: editContext()) else { return true }
478        _ = perform(command)
479        return false
480    }
481}
482
483extension MobileEditor: UIGestureRecognizerDelegate {
484    /// The drawer or block a tap at `point` folds or unfolds: a folded one's `…`, the space after
485    /// its first line, or anywhere on an open drawer's first line.
486    private func foldToggle(at point: CGPoint) -> Int? {
487        guard let manager = textView.textLayoutManager, let content = manager.textContentManager else { return nil }
488        let inContainer = CGPoint(x: point.x - textView.textContainerInset.left, y: point.y - textView.textContainerInset.top)
489        guard let fragment = manager.textLayoutFragment(for: inContainer), let range = fragment.textElement?.elementRange else { return nil }
490        let start = content.offset(from: content.documentRange.location, to: range.location)
491        guard let line = fragment.textLineFragments.first(where: { $0.characterRange.length > 0 }) ?? fragment.textLineFragments.first else { return nil }
492        if hidden.isFolded(start) { return inContainer.x - fragment.layoutFragmentFrame.minX >= line.typographicBounds.maxX ? start : nil }
493        guard Wrappers.starting(at: start, in: document.tree)?.kind == .drawer,
494              inContainer.y - fragment.layoutFragmentFrame.minY < line.typographicBounds.maxY else { return nil }
495        return start
496    }
497
498    /// A tap on a fold's `…` opens it, and one on an open drawer's first line folds it, as TAB
499    /// on the line does.
500    @objc fileprivate func tappedFold(_ tap: UITapGestureRecognizer) {
501        guard let start = foldToggle(at: tap.location(in: textView)),
502              let next = Presentation.cycle(at: start, in: document.tree, fold) else { return }
503        setFolds(next)
504    }
505
506    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
507        foldToggle(at: gestureRecognizer.location(in: textView)) != nil
508    }
509
510    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer) -> Bool {
511        true
512    }
513}
514
515extension MobileEditor: NSTextStorageDelegate {
516    nonisolated func textStorage(
517        _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorage.EditActions, range editedRange: NSRange, changeInLength delta: Int
518    ) {
519        guard editedMask.contains(.editedCharacters) else { return }
520        MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
521    }
522}
523
524extension MobileEditor: NSTextContentStorageDelegate {
525    /// Folded text isn't enumerated, so it isn't laid out or drawn.
526    nonisolated func textContentManager(
527        _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
528    ) -> Bool {
529        guard let range = textElement.elementRange else { return true }
530        let documentStart = textContentManager.documentRange.location
531        let start = textContentManager.offset(from: documentStart, to: range.location)
532        let end = textContentManager.offset(from: documentStart, to: range.endLocation)
533        return !hidden.covers(start, end)
534    }
535}
536
537extension MobileEditor: NSTextLayoutManagerDelegate {
538    /// Folded headings, drawers and blocks end with `…`; blocks are on a band; image lines
539    /// show their image; pretty entities draw their character.
540    nonisolated func textLayoutManager(
541        _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
542    ) -> NSTextLayoutFragment {
543        let range = textElement.elementRange
544        guard let range, let manager = textLayoutManager.textContentManager else { return NSTextLayoutFragment(textElement: textElement, range: range) }
545        let offset = manager.offset(from: manager.documentRange.location, to: range.location)
546        let folded = hidden.isFolded(offset)
547        let band = shaded.containing(offset) != nil ? fragmentStyle.blockBand : nil
548        let string = (textElement as? NSTextParagraph)?.attributedString
549        let image = string.flatMap(OrgLineFragment.image)
550        let entities = string.map(OrgLineFragment.hasEntities) ?? false
551        guard folded || band != nil || image != nil || entities else { return NSTextLayoutFragment(textElement: textElement, range: range) }
552        let fragment = OrgLineFragment(textElement: textElement, range: range)
553        fragment.folded = folded
554        fragment.band = band
555        if band != nil {
556            fragment.start = offset
557            fragment.style = fragmentStyle
558        }
559        fragment.image = image
560        return fragment
561    }
562}
563#endif