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