Sources/OrgstarMobile/MobileEditor.swift

524b5afe95ec3f3e3d1daba761a9e181f09cf88a
orgstar/Sources/OrgstarMobile/MobileEditor.swift history · blame · raw

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