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