Sources/OrgstarMobile/MobileEditor.swift
564 lines · 27189 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", "app.table-import": return onAppCommand != nil
301 case "app.table-export": return onAppCommand != nil && ImportTable.exportText(context.text, at: context.caret, path: "") != nil
302 case "app.refile", "app.refile.copy": return onAppCommand != nil && Presentation.heading(containing: context.caret, in: context.tree) != nil
303 case _ where Self.linkCommands.contains(id): return onAppCommand != nil
304 case "org.link.open": return OpenLinkAtPoint().applies(in: context)
305 case "org.table.toggle-column-width", "org.table.shrink", "org.table.expand":
306 return TableShrink.table(at: context.caret, in: context.text) != nil
307 default: return false
308 }
309 }
310
311 // MARK: - Hardware keyboard
312
313 lazy var dispatcher = KeyDispatcher(keymap: keymap)
314
315 private static let named: [UIKeyboardHIDUsage: String] = [
316 .keyboardTab: "TAB", .keyboardReturnOrEnter: "RET", .keypadEnter: "RET", .keyboardSpacebar: "SPC",
317 .keyboardEscape: "ESC", .keyboardDeleteOrBackspace: "DEL", .keyboardDeleteForward: "<delete>",
318 .keyboardLeftArrow: "<left>", .keyboardRightArrow: "<right>", .keyboardUpArrow: "<up>", .keyboardDownArrow: "<down>",
319 .keyboardHome: "<home>", .keyboardEnd: "<end>", .keyboardPageUp: "<prior>", .keyboardPageDown: "<next>",
320 ]
321
322 /// A key press as a chord; Option is Meta, as `option-as-meta` makes it on the Mac.
323 static func chord(_ key: UIKey) -> KeyChord? {
324 var modifiers: KeyChord.Modifiers = []
325 let flags = key.modifierFlags
326 if flags.contains(.control) { modifiers.insert(.control) }
327 if flags.contains(.alternate) { modifiers.insert(.meta) }
328 if flags.contains(.command) { modifiers.insert(.command) }
329 if let name = named[key.keyCode] {
330 if flags.contains(.shift) { modifiers.insert(.shift) }
331 return KeyChord(name, modifiers)
332 }
333 var characters = key.charactersIgnoringModifiers
334 if flags.contains(.shift), characters.count == 1, characters.lowercased() == characters { characters = characters.uppercased() }
335 guard characters.count == 1 else { return nil }
336 return KeyChord(characters, modifiers)
337 }
338
339 /// The Emacs keymap's commands on an iPad keyboard. Keys it doesn't bind, Command shortcuts
340 /// and editing keys (C-a, C-e, C-k...) are the text system's.
341 func handleKey(_ key: UIKey) -> Bool {
342 guard let chord = Self.chord(key), !chord.modifiers.contains(.command) else { return false }
343 if modal { return handleModal(chord) }
344 // Option alone types characters unless it begins a binding.
345 if chord.modifiers == [.meta], dispatcher.pending.isEmpty,
346 keymap.candidates(for: [chord]).isEmpty, !keymap.isPrefix([chord]) { return false }
347 switch dispatcher.feed(chord) {
348 case .pending(let keys):
349 onMessage?(KeySequence.format(keys) + "-")
350 return true
351 case .cancelled:
352 onMessage?("Quit")
353 return true
354 case .undefined(let keys):
355 onMessage?("\(KeySequence.format(keys)) is undefined")
356 return true
357 case .unbound:
358 return false
359 case .complete(let keys, let candidates):
360 let context = editContext()
361 let runnable = candidates.first { binding in
362 (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
363 }
364 // A sequence runs its command even where it doesn't apply, which says why, as on the Mac.
365 guard let binding = runnable ?? (keys.count > 1 ? candidates.first : nil) else { return false }
366 if keys.count == 1, binding.command.hasPrefix("edit."), !["edit.undo", "edit.redo"].contains(binding.command) { return false }
367 run(binding.command)
368 return true
369 }
370 }
371
372 func editContext() -> EditContext {
373 EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: selection, hidden: hidden.all, options: options, knownTags: knownTags)
374 }
375
376 private func openLinkAtCaret() {
377 let caret = textView.selectedRange.location
378 if let link = Links.link(at: caret, text: document.text, tree: document.tree)?.link {
379 onLink?(link)
380 } else if let days = Links.timestampDays(at: caret, text: document.text) {
381 onAgenda?(days.start, days.count)
382 } else {
383 onMessage?("No link here")
384 }
385 }
386
387 // MARK: - Editing
388
389 /// Applies `edits` (against the current text) through the text view as one undo step.
390 func applyEdits(_ edits: [TextEdit]) {
391 let interval = Perf.begin("editor.applyEdits")
392 defer { interval.end() }
393 guard !edits.isEmpty else { return }
394 applyingEdits = true
395 defer { applyingEdits = false }
396 // Straight into the storage: replacing through text input would take the active
397 // keyboard's substitutions (smart dashes) when another view has the keyboard.
398 let storage = textView.textStorage
399 let old = storage.string as NSString
400 // By lines, so a fold between two changes stays.
401 let ascending = edits.flatMap { splitByLines($0, in: storage.string) }.sorted { $0.range.lowerBound < $1.range.lowerBound }
402 var inverse: [TextEdit] = []
403 var delta = 0
404 for edit in ascending {
405 let start = edit.range.lowerBound + delta
406 let length = (edit.replacement as NSString).length
407 inverse.append(TextEdit(range: start..<start + length, replacement: old.substring(with: NSRange(edit.range))))
408 delta += length - edit.range.count
409 }
410 let caret = textView.selectedRange
411 // One at a time, last first: each is processed alone, so folds between them stay.
412 for edit in ascending.reversed() {
413 storage.replaceCharacters(in: NSRange(edit.range), with: edit.replacement)
414 }
415 textView.undoManager?.registerUndo(withTarget: self) { editor in
416 editor.applyEdits(inverse)
417 editor.textView.selectedRange = caret
418 }
419 }
420
421 /// The storage changed (typing, a command, undo): the document takes the same edit, and
422 /// folds and styles follow.
423 fileprivate func storageEdited(range: NSRange, delta: Int) {
424 let interval = Perf.begin("editor.edit")
425 defer { interval.end() }
426 guard !loading else { return }
427 let old = range.location..<(range.location + range.length - delta)
428 let replacement = (textView.textStorage.string as NSString).substring(with: range)
429 let edit = TextEdit(range: old, replacement: replacement)
430 do {
431 try document.apply([edit], baseRevision: document.revision)
432 } catch {
433 // Out of step: the view's text wins.
434 shrunk = ShrunkColumns()
435 load(textView.textStorage.string)
436 return
437 }
438 for table in shrunk.map(through: edit, in: textView.textStorage.string, command: commandEditing) { scheduleRestyle(table) }
439 fold = FoldState(
440 folds: Self.map(fold.folds, old, delta), bodyFolds: Self.map(fold.bodyFolds, old, delta),
441 wrapperFolds: Self.map(fold.wrapperFolds, old, delta)
442 )
443 scheduleRestyle(range.location..<NSMaxRange(range))
444 onChange?()
445 }
446
447 /// Starts after the edit move with it; ones inside it go.
448 static func map(_ starts: Set<Int>, _ old: Range<Int>, _ delta: Int) -> Set<Int> {
449 Set(starts.compactMap { start in
450 if start >= old.upperBound { return start + delta }
451 return start <= old.lowerBound ? start : nil
452 })
453 }
454
455}
456
457extension MobileEditor: UITextViewDelegate {
458 func textViewDidChangeSelection(_ textView: UITextView) {
459 selectionChanged()
460 }
461
462 /// `electric-pair-mode` for typed brackets and quotes, DEL and RET, from either keyboard.
463 func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
464 if !applyingEdits { typedOutsideInsert() }
465 guard options.electricPair, !applyingEdits, textView.markedTextRange == nil else { return true }
466 let selected = textView.selectedRange
467 let key: String
468 if text.isEmpty, selected.length == 0, range.length == 1, NSMaxRange(range) == selected.location {
469 key = "DEL"
470 } else if range == selected, text == "\n" {
471 key = "RET"
472 } else if range == selected, ElectricPairKey.characters.contains(text) {
473 key = text
474 } else {
475 return true
476 }
477 let command = ElectricPairKey(key: key)
478 guard command.applies(in: editContext()) else { return true }
479 _ = perform(command)
480 return false
481 }
482}
483
484extension MobileEditor: UIGestureRecognizerDelegate {
485 /// The drawer or block a tap at `point` folds or unfolds: a folded one's `…`, the space after
486 /// its first line, or anywhere on an open drawer's first line.
487 private func foldToggle(at point: CGPoint) -> Int? {
488 guard let manager = textView.textLayoutManager, let content = manager.textContentManager else { return nil }
489 let inContainer = CGPoint(x: point.x - textView.textContainerInset.left, y: point.y - textView.textContainerInset.top)
490 guard let fragment = manager.textLayoutFragment(for: inContainer), let range = fragment.textElement?.elementRange else { return nil }
491 let start = content.offset(from: content.documentRange.location, to: range.location)
492 guard let line = fragment.textLineFragments.first(where: { $0.characterRange.length > 0 }) ?? fragment.textLineFragments.first else { return nil }
493 if hidden.isFolded(start) { return inContainer.x - fragment.layoutFragmentFrame.minX >= line.typographicBounds.maxX ? start : nil }
494 guard Wrappers.starting(at: start, in: document.tree)?.kind == .drawer,
495 inContainer.y - fragment.layoutFragmentFrame.minY < line.typographicBounds.maxY else { return nil }
496 return start
497 }
498
499 /// A tap on a fold's `…` opens it, and one on an open drawer's first line folds it, as TAB
500 /// on the line does.
501 @objc fileprivate func tappedFold(_ tap: UITapGestureRecognizer) {
502 guard let start = foldToggle(at: tap.location(in: textView)),
503 let next = Presentation.cycle(at: start, in: document.tree, fold) else { return }
504 setFolds(next)
505 }
506
507 func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
508 foldToggle(at: gestureRecognizer.location(in: textView)) != nil
509 }
510
511 func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer) -> Bool {
512 true
513 }
514}
515
516extension MobileEditor: NSTextStorageDelegate {
517 nonisolated func textStorage(
518 _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorage.EditActions, range editedRange: NSRange, changeInLength delta: Int
519 ) {
520 guard editedMask.contains(.editedCharacters) else { return }
521 MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
522 }
523}
524
525extension MobileEditor: NSTextContentStorageDelegate {
526 /// Folded text isn't enumerated, so it isn't laid out or drawn.
527 nonisolated func textContentManager(
528 _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
529 ) -> Bool {
530 guard let range = textElement.elementRange else { return true }
531 let documentStart = textContentManager.documentRange.location
532 let start = textContentManager.offset(from: documentStart, to: range.location)
533 let end = textContentManager.offset(from: documentStart, to: range.endLocation)
534 return !hidden.covers(start, end)
535 }
536}
537
538extension MobileEditor: NSTextLayoutManagerDelegate {
539 /// Folded headings, drawers and blocks end with `…`; blocks are on a band; image lines
540 /// show their image; pretty entities draw their character.
541 nonisolated func textLayoutManager(
542 _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
543 ) -> NSTextLayoutFragment {
544 let range = textElement.elementRange
545 guard let range, let manager = textLayoutManager.textContentManager else { return NSTextLayoutFragment(textElement: textElement, range: range) }
546 let offset = manager.offset(from: manager.documentRange.location, to: range.location)
547 let folded = hidden.isFolded(offset)
548 let band = shaded.containing(offset) != nil ? fragmentStyle.blockBand : nil
549 let string = (textElement as? NSTextParagraph)?.attributedString
550 let image = string.flatMap(OrgLineFragment.image)
551 let entities = string.map(OrgLineFragment.hasEntities) ?? false
552 guard folded || band != nil || image != nil || entities else { return NSTextLayoutFragment(textElement: textElement, range: range) }
553 let fragment = OrgLineFragment(textElement: textElement, range: range)
554 fragment.folded = folded
555 fragment.band = band
556 if band != nil {
557 fragment.start = offset
558 fragment.style = fragmentStyle
559 }
560 fragment.image = image
561 return fragment
562 }
563}
564#endif