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