Sources/OrgstarMobile/MobileEditor.swift
600 lines · 29764 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 /// An incremental search in progress, and the last search string, for C-s C-s.
45 var isearch: ISearch?
46 static var lastISearch: String?
47 /// `auto-fill-mode` for this buffer: the settings' unless toggled here.
48 var autoFillOverride: Bool?
49 var autoFills: Bool { autoFillOverride ?? options.autoFill }
50 var keymap = KeymapPreset.emacs.keymap {
51 didSet { dispatcher = KeyDispatcher(keymap: keymap) }
52 }
53 /// The Doom preset's modal editing, and its state: the engine, the caret in visual
54 /// states, marks, the jump list, what insert state began with, and macros.
55 var modal = false {
56 didSet {
57 if modal != oldValue { vim = Vim() }
58 updateCursor()
59 }
60 }
61 var vim = Vim()
62 var visualCaret: Int?
63 var vimMarks: [Character: Int] = [:]
64 var jumpList: [Int] = []
65 var jumpIndex = 0
66 var insertSnapshot: String?
67 var recordingRegister: Character?
68 var recordedKeys: [KeyChord] = []
69 var replayingMacro = 0
70 static var vimRegisters: [Character: (text: String, linewise: Bool)] = [:]
71 static var vimClipboardRecord: (text: String, linewise: Bool)?
72 static var macros: [Character: [KeyChord]] = [:]
73 /// What `:`, `/` and `?` read, oldest first, for `q:`.
74 static var promptHistory: [String: [String]] = [:]
75 var onChange: (() -> Void)?
76 var onMessage: ((String) -> Void)?
77 var onPrompt: ((Prompt, @escaping (String?) -> Void) -> Void)?
78 var onLink: ((OrgLink) -> Void)?
79 /// Edits being applied, which the typing hooks leave alone.
80 private var applyingEdits = false
81 /// Source blocks to write to their files (C-c C-v t).
82 var onTangle: ((Tangle.Scope) -> Void)?
83 /// A source block to run (C-c C-c).
84 var onBabel: ((BabelJob) -> Void)?
85 /// The file's setup files to read again (C-c C-c on a keyword line).
86 var onRefreshSetup: (() -> Void)?
87 /// A block, a table's formulas or a field to edit apart (C-c ', C-c `).
88 var onEditBlock: ((BlockEdit) -> Void)?
89 /// A followed timestamp's agenda days: the first (a `Days` number) and how many.
90 var onAgenda: ((Int, Int) -> Void)?
91 /// Shows a column view.
92 var onColumnView: ((ColumnView.View) -> Void)?
93 /// Commands the app runs, as `app.clock.in`.
94 var onAppCommand: ((String) -> Void)?
95 /// Tags used across the workspace, for completion.
96 var knownTags: @Sendable () -> [String] = { [] }
97
98 var theme: MobileTheme
99 internal(set) var fold = FoldState()
100 var globalVisibility: GlobalVisibility?
101 let hidden = LockedRanges()
102 /// Blocks drawn on a band.
103 let shaded = LockedRanges()
104 let fragmentStyle = FragmentStyle()
105 var selectionColor: UIColor = .clear
106 /// `org-indent-mode` and `org-hide-leading-stars`, from the settings and `#+STARTUP`.
107 var indented = true
108 var hideStars = false
109 /// One paragraph style per indent pair.
110 var paragraphStyles: [[Int]: NSParagraphStyle] = [:]
111 /// The line last revealed while markup is hidden, to hide again when the caret leaves.
112 var revealedLine: NSRange?
113 /// `org-toggle-inline-images`: lines that are only an image link show the image.
114 internal(set) var showsImages = false
115 /// `org-latex-preview`: LaTeX fragments show as typeset math.
116 internal(set) var showsLatex = false
117 /// The view width images were last sized for.
118 var imageWidth: CGFloat = 0
119 /// The file's folder, for relative image paths.
120 let baseDirectory: URL?
121 static let imageCache = NSCache<NSString, UIImage>()
122 var loading = false
123 var restyleScheduled: Range<Int>?
124 /// Narrowed table columns (`org-table-shrink`).
125 var shrunk = ShrunkColumns()
126 /// A command's edits being applied, which keep shrunk columns narrow.
127 private var commandEditing = false
128
129 init(
130 document: DocumentState, editable: Bool, options: EditingOptions = .org, theme spec: ThemeSpec = .default,
131 showMarkup: Bool = true, baseDirectory: URL? = nil
132 ) {
133 self.document = document
134 self.options = options
135 self.showMarkup = showMarkup
136 self.baseDirectory = baseDirectory
137 theme = MobileTheme(spec)
138 let keyed = KeyedTextView(usingTextLayoutManager: true)
139 textView = keyed
140 super.init()
141 keyed.keyHandler = { [weak self] key in self?.handleKey(key) ?? false }
142 keyed.onLayout = { [weak self] in self?.viewResized() }
143 textView.isEditable = editable
144 textView.autocorrectionType = .no
145 textView.autocapitalizationType = .none
146 textView.smartQuotesType = .no
147 textView.smartDashesType = .no
148 textView.smartInsertDeleteType = .no
149 textView.spellCheckingType = options.spellCheck ? .yes : .no
150 textView.keyboardDismissMode = .interactive
151 textView.alwaysBounceVertical = true
152 textView.textContainerInset = UIEdgeInsets(top: 12, left: 8, bottom: 24, right: 8)
153 textView.delegate = self
154 textView.textStorage.delegate = self
155 textView.textLayoutManager?.delegate = self
156 (textView.textLayoutManager?.textContentManager as? NSTextContentStorage)?.delegate = self
157 let foldTap = UITapGestureRecognizer(target: self, action: #selector(tappedFold))
158 foldTap.delegate = self
159 textView.addGestureRecognizer(foldTap)
160 let startup = Presentation.startupDisplay(document.tree, options: options)
161 indented = startup.indented
162 hideStars = startup.hideStars
163 showsImages = startup.inlineImages
164 showsLatex = startup.latexPreview
165 shrunk = ShrunkColumns.startup(document.tree)
166 applyThemeToView()
167 load(document.text)
168 setFolds(startup.folds)
169 if startup.alignTables { _ = perform(AlignAllTables()) }
170 truncatesLines = startup.truncated
171 textView.selectedRange = NSRange(location: 0, length: 0)
172 }
173
174 // MARK: - DocumentBuffer
175
176 var selection: [Range<Int>] {
177 let selected = textView.selectedRange
178 return [selected.location..<NSMaxRange(selected)]
179 }
180
181 func update<T>(_ change: (inout DocumentState) throws -> T) rethrows -> T {
182 let before = document.text
183 let defaultsBefore = document.defaults
184 let selected = textView.selectedRange
185 let result = try change(&document)
186 if document.text != before {
187 // A save that merged a change from disk, or a revert: the view shows the new text.
188 shrunk = ShrunkColumns()
189 load(document.text)
190 let length = (document.text as NSString).length
191 textView.selectedRange = NSRange(location: min(selected.location, length), length: 0)
192 textView.undoManager?.removeAllActions()
193 setFolds(fold)
194 } else if document.defaults != defaultsBefore {
195 restyle(0..<(document.text as NSString).length)
196 }
197 return result
198 }
199
200 func perform(_ command: any OrgCommand, now: Date = Date(), answers: [String: String] = [:]) -> CommandStep {
201 let context = EditContext(
202 revision: document.revision, text: document.text, tree: document.tree, selection: selection,
203 now: now, answers: answers, hidden: hidden.all, options: options, knownTags: knownTags
204 )
205 let step = command.run(in: context)
206 switch step {
207 case .commit(let result):
208 guard textView.isEditable || result.edits.isEmpty else {
209 onMessage?("This file is read-only.")
210 return .failed("read-only")
211 }
212 commandEditing = true
213 applyEdits(result.edits)
214 commandEditing = false
215 if let selected = result.selection?.first {
216 unfold(around: selected.lowerBound)
217 textView.selectedRange = NSRange(location: selected.lowerBound, length: selected.count)
218 textView.scrollRangeToVisible(textView.selectedRange)
219 }
220 for effect in result.effects {
221 switch effect {
222 case .message(let text): onMessage?(text)
223 case .fold(let start):
224 var state = fold
225 state.folds.insert(start)
226 setFolds(state)
227 case .refreshSetup: onRefreshSetup?()
228 case .timer(let timer): TimerModel.shared.set(timer)
229 default: break
230 }
231 }
232 case .failed(let message):
233 onMessage?(message)
234 case .prompt(let prompt):
235 onPrompt?(prompt) { [weak self] answer in
236 guard let self else { return }
237 guard let answer else { return self.onMessage?("Quit") ?? () }
238 _ = self.perform(command, now: now, answers: answers.merging([prompt.key: answer]) { $1 })
239 }
240 case .external(.editBlock(let edit)) where onEditBlock != nil:
241 onEditBlock?(edit)
242 case .external(.babel(let job)) where onBabel != nil:
243 onBabel?(job)
244 case .external(.tangle(let scope)) where onTangle != nil:
245 onTangle?(scope)
246 case .external(.agenda(let start, let count)) where onAgenda != nil:
247 onAgenda?(start, count)
248 case .external(.columnView(let view)) where onColumnView != nil:
249 onColumnView?(view)
250 case .external(let request):
251 onMessage?(Self.unavailable(request, title: command.title))
252 }
253 return step
254 }
255
256 /// Why a request the app doesn't handle did nothing: only table recalculation needs Emacs.
257 static func unavailable(_ request: ExternalRequest, title: String) -> String {
258 if case .emacsTable(_, _, _, let reason, _) = request { return "This table needs Emacs, which runs on the Mac: \(reason)." }
259 return "\(title) isn't available on iPhone and iPad."
260 }
261
262 // MARK: - Commands by name and key
263
264 /// Runs what `keys` (as `C-c C-t`) is bound to in the Emacs keymap, for the caret's context.
265 func run(keys: String) {
266 guard let chords = KeySequence.parse(keys) else { return }
267 let context = editContext()
268 let binding = keymap.candidates(for: chords).first { binding in
269 (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
270 }
271 guard let binding else { return onMessage?("Nothing to do here") ?? () }
272 run(binding.command)
273 }
274
275 func run(_ id: String) {
276 switch id {
277 case "org.cycle":
278 if !cycleAtCaret() { onMessage?("Not on a heading, drawer or block") }
279 case "org.cycle-global": cycleGlobal()
280 case "org.link.open": openLinkAtCaret()
281 case "org.toggle-inline-images": toggleImages()
282 case "org.latex-preview": toggleLatex()
283 case "editor.toggle-truncate-lines":
284 truncatesLines.toggle()
285 onMessage?(truncatesLines ? "Truncate long lines enabled" : "Truncate long lines disabled")
286 case "edit.isearch-forward": startISearch(forward: true)
287 case "edit.isearch-backward": startISearch(forward: false)
288 case "edit.isearch-forward-regexp": startISearch(forward: true, regexp: true)
289 case "edit.isearch-backward-regexp": startISearch(forward: false, regexp: true)
290 case "editor.toggle-auto-fill":
291 autoFillOverride = !autoFills
292 onMessage?(autoFills ? "Auto-Fill mode enabled in current buffer" : "Auto-Fill mode disabled in current buffer")
293 case "edit.undo": textView.undoManager?.undo()
294 case "edit.redo": textView.undoManager?.redo()
295 case "org.table.toggle-column-width", "org.table.shrink", "org.table.expand": tableColumnWidth(id)
296 case _ where id.hasPrefix("app.") || Self.linkCommands.contains(id):
297 if let onAppCommand { onAppCommand(id) } else { onMessage?("Not available on iOS yet") }
298 default:
299 if let command = Commands.command(id) {
300 _ = perform(command)
301 } else {
302 onMessage?("Not available on iOS yet")
303 }
304 }
305 }
306
307 /// Link commands that need the stored links or the file, which the screen has.
308 static let linkCommands: Set<String> = ["org.link.store", "org.id.store-link", "org.link.insert"]
309
310 func applies(_ id: String, in context: EditContext) -> Bool {
311 if let command = Commands.command(id) { return command.applies(in: context) }
312 switch id {
313 case "org.cycle":
314 return Presentation.heading(containing: context.caret, in: context.tree) != nil || Wrappers.toggleable(at: context.caret, in: context.tree) != nil
315 case "org.cycle-global", "edit.undo", "edit.redo", "org.toggle-inline-images", "org.latex-preview", "editor.toggle-truncate-lines",
316 "editor.toggle-auto-fill", "edit.isearch-forward", "edit.isearch-backward",
317 "edit.isearch-forward-regexp", "edit.isearch-backward-regexp": return true
318 case "app.clock.in", "app.clock.out", "app.clock.cancel", "app.clock.goto", "app.clock.in-recent", "app.clock.in-last",
319 "app.clock.goto-recent", "app.clock.default", "app.clock.resolve", "app.toggle-markup": return onAppCommand != nil
320 case "app.refile.goto", "app.table-import", "app.crypt.encrypt-entries", "app.crypt.forget-passphrase", "app.attach.attach", "app.attach.url",
321 "app.attach.new", "app.attach.open", "app.attach.reveal", "app.attach.delete", "app.attach.delete-all", "app.attach.sync",
322 "app.attach.set-directory", "app.attach.unset-directory", "app.backlinks", "app.node.find", "app.node.insert": return onAppCommand != nil
323 case _ where id.hasPrefix("app.dailies."): return onAppCommand != nil
324 case "app.crypt.encrypt-entry": return onAppCommand != nil && OrgCrypt.heading(context.text, at: context.caret) != nil && OrgCrypt.encryptedRange(context.text, at: context.caret) == nil
325 case "app.crypt.open-entry", "app.crypt.decrypt-entry": return onAppCommand != nil && OrgCrypt.encryptedRange(context.text, at: context.caret) != nil
326 case "app.table-export", "app.plot": return onAppCommand != nil && ImportTable.exportText(context.text, at: context.caret, path: "") != nil
327 case "app.refile", "app.refile.copy": return onAppCommand != nil && Presentation.heading(containing: context.caret, in: context.tree) != nil
328 case _ where Self.linkCommands.contains(id): return onAppCommand != nil
329 case "org.link.open": return OpenLinkAtPoint().applies(in: context)
330 case "org.table.toggle-column-width", "org.table.shrink", "org.table.expand":
331 return TableShrink.table(at: context.caret, in: context.text) != nil
332 default: return false
333 }
334 }
335
336 // MARK: - Hardware keyboard
337
338 lazy var dispatcher = KeyDispatcher(keymap: keymap)
339
340 private static let named: [UIKeyboardHIDUsage: String] = [
341 .keyboardTab: "TAB", .keyboardReturnOrEnter: "RET", .keypadEnter: "RET", .keyboardSpacebar: "SPC",
342 .keyboardEscape: "ESC", .keyboardDeleteOrBackspace: "DEL", .keyboardDeleteForward: "<delete>",
343 .keyboardLeftArrow: "<left>", .keyboardRightArrow: "<right>", .keyboardUpArrow: "<up>", .keyboardDownArrow: "<down>",
344 .keyboardHome: "<home>", .keyboardEnd: "<end>", .keyboardPageUp: "<prior>", .keyboardPageDown: "<next>",
345 ]
346
347 /// A key press as a chord; Option is Meta, as `option-as-meta` makes it on the Mac.
348 static func chord(_ key: UIKey) -> KeyChord? {
349 var modifiers: KeyChord.Modifiers = []
350 let flags = key.modifierFlags
351 if flags.contains(.control) { modifiers.insert(.control) }
352 if flags.contains(.alternate) { modifiers.insert(.meta) }
353 if flags.contains(.command) { modifiers.insert(.command) }
354 if let name = named[key.keyCode] {
355 if flags.contains(.shift) { modifiers.insert(.shift) }
356 return KeyChord(name, modifiers)
357 }
358 var characters = key.charactersIgnoringModifiers
359 if flags.contains(.shift), characters.count == 1, characters.lowercased() == characters { characters = characters.uppercased() }
360 guard characters.count == 1 else { return nil }
361 return KeyChord(characters, modifiers)
362 }
363
364 /// The Emacs keymap's commands on an iPad keyboard. Keys it doesn't bind, Command shortcuts
365 /// and editing keys (C-a, C-e, C-k...) are the text system's.
366 func handleKey(_ key: UIKey) -> Bool {
367 guard let chord = Self.chord(key), !chord.modifiers.contains(.command) else { return false }
368 if isearch != nil, isearchKey(chord) { return true }
369 if modal { return handleModal(chord) }
370 // Option alone types characters unless it begins a binding.
371 if chord.modifiers == [.meta], dispatcher.pending.isEmpty,
372 keymap.candidates(for: [chord]).isEmpty, !keymap.isPrefix([chord]) { return false }
373 switch dispatcher.feed(chord) {
374 case .pending(let keys):
375 onMessage?(KeySequence.format(keys) + "-")
376 return true
377 case .cancelled:
378 onMessage?("Quit")
379 return true
380 case .undefined(let keys):
381 onMessage?("\(KeySequence.format(keys)) is undefined")
382 return true
383 case .unbound:
384 return false
385 case .complete(let keys, let candidates):
386 let context = editContext()
387 let runnable = candidates.first { binding in
388 (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
389 }
390 // A sequence runs its command even where it doesn't apply, which says why, as on the Mac.
391 guard let binding = runnable ?? (keys.count > 1 ? candidates.first : nil) else { return false }
392 if keys.count == 1, binding.command.hasPrefix("edit."), !["edit.undo", "edit.redo"].contains(binding.command) { return false }
393 run(binding.command)
394 return true
395 }
396 }
397
398 func editContext() -> EditContext {
399 EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: selection, hidden: hidden.all, options: options, knownTags: knownTags)
400 }
401
402 private func openLinkAtCaret() {
403 let caret = textView.selectedRange.location
404 if let link = Links.link(at: caret, text: document.text, tree: document.tree)?.link {
405 onLink?(link)
406 } else if let days = Links.timestampDays(at: caret, text: document.text) {
407 onAgenda?(days.start, days.count)
408 } else {
409 onMessage?("No link here")
410 }
411 }
412
413 // MARK: - Editing
414
415 /// Applies `edits` (against the current text) through the text view as one undo step.
416 func applyEdits(_ edits: [TextEdit]) {
417 let interval = Perf.begin("editor.applyEdits")
418 defer { interval.end() }
419 guard !edits.isEmpty else { return }
420 applyingEdits = true
421 defer { applyingEdits = false }
422 // Straight into the storage: replacing through text input would take the active
423 // keyboard's substitutions (smart dashes) when another view has the keyboard.
424 let storage = textView.textStorage
425 let old = storage.string as NSString
426 // By lines, so a fold between two changes stays.
427 let ascending = edits.flatMap { splitByLines($0, in: storage.string) }.sorted { $0.range.lowerBound < $1.range.lowerBound }
428 var inverse: [TextEdit] = []
429 var delta = 0
430 for edit in ascending {
431 let start = edit.range.lowerBound + delta
432 let length = (edit.replacement as NSString).length
433 inverse.append(TextEdit(range: start..<start + length, replacement: old.substring(with: NSRange(edit.range))))
434 delta += length - edit.range.count
435 }
436 let caret = textView.selectedRange
437 // One at a time, last first: each is processed alone, so folds between them stay.
438 for edit in ascending.reversed() {
439 storage.replaceCharacters(in: NSRange(edit.range), with: edit.replacement)
440 }
441 textView.undoManager?.registerUndo(withTarget: self) { editor in
442 editor.applyEdits(inverse)
443 editor.textView.selectedRange = caret
444 }
445 }
446
447 /// The storage changed (typing, a command, undo): the document takes the same edit, and
448 /// folds and styles follow.
449 fileprivate func storageEdited(range: NSRange, delta: Int) {
450 let interval = Perf.begin("editor.edit")
451 defer { interval.end() }
452 guard !loading else { return }
453 let old = range.location..<(range.location + range.length - delta)
454 let replacement = (textView.textStorage.string as NSString).substring(with: range)
455 let edit = TextEdit(range: old, replacement: replacement)
456 do {
457 try document.apply([edit], baseRevision: document.revision)
458 } catch {
459 // Out of step: the view's text wins.
460 shrunk = ShrunkColumns()
461 load(textView.textStorage.string)
462 return
463 }
464 for table in shrunk.map(through: edit, in: textView.textStorage.string, command: commandEditing) { scheduleRestyle(table) }
465 fold = FoldState(
466 folds: Self.map(fold.folds, old, delta), bodyFolds: Self.map(fold.bodyFolds, old, delta),
467 wrapperFolds: Self.map(fold.wrapperFolds, old, delta)
468 )
469 scheduleRestyle(range.location..<NSMaxRange(range))
470 onChange?()
471 }
472
473 /// Starts after the edit move with it; ones inside it go.
474 static func map(_ starts: Set<Int>, _ old: Range<Int>, _ delta: Int) -> Set<Int> {
475 Set(starts.compactMap { start in
476 if start >= old.upperBound { return start + delta }
477 return start <= old.lowerBound ? start : nil
478 })
479 }
480
481}
482
483extension MobileEditor: UITextViewDelegate {
484 func textViewDidChangeSelection(_ textView: UITextView) {
485 selectionChanged()
486 }
487
488 /// `electric-pair-mode` for typed brackets and quotes, DEL and RET, and `auto-fill-mode`
489 /// for a typed space, from either keyboard.
490 func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
491 if isearch != nil, !applyingEdits {
492 isearchTyped(text)
493 return false
494 }
495 if !applyingEdits { typedOutsideInsert() }
496 if autoFills, !applyingEdits, textView.markedTextRange == nil, text == " ", range == textView.selectedRange {
497 _ = perform(AutoFillSpace())
498 return false
499 }
500 guard options.electricPair, !applyingEdits, textView.markedTextRange == nil else { return true }
501 let selected = textView.selectedRange
502 let key: String
503 if text.isEmpty, selected.length == 0, range.length == 1, NSMaxRange(range) == selected.location {
504 key = "DEL"
505 } else if range == selected, text == "\n" {
506 key = "RET"
507 } else if range == selected, ElectricPairKey.characters.contains(text) {
508 key = text
509 } else {
510 return true
511 }
512 let command = ElectricPairKey(key: key)
513 guard command.applies(in: editContext()) else { return true }
514 _ = perform(command)
515 return false
516 }
517}
518
519extension MobileEditor: UIGestureRecognizerDelegate {
520 /// The drawer or block a tap at `point` folds or unfolds: a folded one's `…`, the space after
521 /// its first line, or anywhere on an open drawer's first line.
522 private func foldToggle(at point: CGPoint) -> Int? {
523 guard let manager = textView.textLayoutManager, let content = manager.textContentManager else { return nil }
524 let inContainer = CGPoint(x: point.x - textView.textContainerInset.left, y: point.y - textView.textContainerInset.top)
525 guard let fragment = manager.textLayoutFragment(for: inContainer), let range = fragment.textElement?.elementRange else { return nil }
526 let start = content.offset(from: content.documentRange.location, to: range.location)
527 guard let line = fragment.textLineFragments.first(where: { $0.characterRange.length > 0 }) ?? fragment.textLineFragments.first else { return nil }
528 if hidden.isFolded(start) { return inContainer.x - fragment.layoutFragmentFrame.minX >= line.typographicBounds.maxX ? start : nil }
529 guard Wrappers.starting(at: start, in: document.tree)?.kind == .drawer,
530 inContainer.y - fragment.layoutFragmentFrame.minY < line.typographicBounds.maxY else { return nil }
531 return start
532 }
533
534 /// A tap on a fold's `…` opens it, and one on an open drawer's first line folds it, as TAB
535 /// on the line does.
536 @objc fileprivate func tappedFold(_ tap: UITapGestureRecognizer) {
537 guard let start = foldToggle(at: tap.location(in: textView)),
538 let next = Presentation.cycle(at: start, in: document.tree, fold) else { return }
539 setFolds(next)
540 }
541
542 func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
543 foldToggle(at: gestureRecognizer.location(in: textView)) != nil
544 }
545
546 func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer) -> Bool {
547 true
548 }
549}
550
551extension MobileEditor: NSTextStorageDelegate {
552 nonisolated func textStorage(
553 _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorage.EditActions, range editedRange: NSRange, changeInLength delta: Int
554 ) {
555 guard editedMask.contains(.editedCharacters) else { return }
556 MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
557 }
558}
559
560extension MobileEditor: NSTextContentStorageDelegate {
561 /// Folded text isn't enumerated, so it isn't laid out or drawn.
562 nonisolated func textContentManager(
563 _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
564 ) -> Bool {
565 guard let range = textElement.elementRange else { return true }
566 let documentStart = textContentManager.documentRange.location
567 let start = textContentManager.offset(from: documentStart, to: range.location)
568 let end = textContentManager.offset(from: documentStart, to: range.endLocation)
569 return !hidden.covers(start, end)
570 }
571}
572
573extension MobileEditor: NSTextLayoutManagerDelegate {
574 /// Folded headings, drawers and blocks end with `…`; blocks are on a band; image lines
575 /// show their image; pretty entities draw their character.
576 nonisolated func textLayoutManager(
577 _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
578 ) -> NSTextLayoutFragment {
579 let range = textElement.elementRange
580 guard let range, let manager = textLayoutManager.textContentManager else { return NSTextLayoutFragment(textElement: textElement, range: range) }
581 let offset = manager.offset(from: manager.documentRange.location, to: range.location)
582 let folded = hidden.isFolded(offset)
583 let band = shaded.containing(offset) != nil ? fragmentStyle.blockBand : nil
584 let string = (textElement as? NSTextParagraph)?.attributedString
585 let image = string.flatMap(OrgLineFragment.image)
586 let entities = string.map(OrgLineFragment.hasEntities) ?? false
587 let latex = string.map(OrgLineFragment.hasLatex) ?? false
588 guard folded || band != nil || image != nil || entities || latex else { return NSTextLayoutFragment(textElement: textElement, range: range) }
589 let fragment = OrgLineFragment(textElement: textElement, range: range)
590 fragment.folded = folded
591 fragment.band = band
592 if band != nil {
593 fragment.start = offset
594 fragment.style = fragmentStyle
595 }
596 fragment.image = image
597 return fragment
598 }
599}
600#endif