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