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