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