Sources/OrgstarMobile/MobileEditor.swift
1102 lines · 54623 bytes
1#if os(iOS)
2import OrgApp
3import OrgCore
4import OrgDocument
5import OrgHighlight
6import OrgPresentation
7import UIKit
8
9/// Ranges read by TextKit's delegate callbacks.
10final class LockedRanges: @unchecked Sendable {
11 private let lock = NSLock()
12 private var ranges: [Range<Int>] = []
13 private var starts: Set<Int> = []
14
15 func set(_ new: [Range<Int>], folded: Set<Int>) { lock.withLock { ranges = new; starts = folded } }
16 var all: [Range<Int>] { lock.withLock { ranges } }
17 func covers(_ start: Int, _ end: Int) -> Bool { lock.withLock { ranges.contains { $0.lowerBound <= start && end <= $0.upperBound } } }
18 func isFolded(_ start: Int) -> Bool { lock.withLock { starts.contains(start) } }
19 func containing(_ offset: Int) -> Range<Int>? { lock.withLock { ranges.first { $0.contains(offset) } } }
20}
21
22/// What layout fragments draw beyond the text, read by TextKit's delegate callbacks.
23final class FragmentStyle: @unchecked Sendable {
24 private let lock = NSLock()
25 private var band: (color: UIColor, width: CGFloat) = (.clear, 0)
26 private var selected: (range: Range<Int>, color: UIColor)?
27
28 func set(blockBackground color: UIColor, width: CGFloat) { lock.withLock { band = (color, width) } }
29 var blockBand: (color: UIColor, width: CGFloat) { lock.withLock { band } }
30 /// The selection, which a block's fragment draws over its band, as the Mac's fragments do.
31 func set(selection range: Range<Int>?, color: UIColor) { lock.withLock { selected = range.map { ($0, color) } } }
32 var selection: (range: Range<Int>, color: UIColor)? { lock.withLock { selected } }
33}
34
35/// A text view that offers hardware-keyboard presses to the editor's keymap first.
36final class KeyedTextView: UITextView {
37 var keyHandler: ((UIKey) -> Bool)?
38 /// Keys the editor took, whose release the text system doesn't see. Optional: made by
39 /// UIKit's `init(usingTextLayoutManager:)`, the view skips Swift's default values.
40 private var handled: Set<UIKeyboardHIDUsage>?
41 /// Called after each layout pass, as the view's size settles.
42 var onLayout: (() -> Void)?
43 /// The text container's width while lines are truncated.
44 static let truncatedWidth: CGFloat = 100_000
45
46 /// Long lines run off the right edge and the view scrolls sideways.
47 var truncates: Bool {
48 get { !textContainer.widthTracksTextView }
49 set {
50 textContainer.widthTracksTextView = !newValue
51 if newValue {
52 textContainer.size = CGSize(width: Self.truncatedWidth, height: CGFloat.greatestFiniteMagnitude)
53 } else {
54 textContainer.size = CGSize(width: bounds.width - textContainerInset.left - textContainerInset.right, height: CGFloat.greatestFiniteMagnitude)
55 contentOffset.x = 0
56 }
57 showsHorizontalScrollIndicator = newValue
58 setNeedsLayout()
59 }
60 }
61
62 override func layoutSubviews() {
63 // The text view sets its container's width to its own when it lays out.
64 if truncates, textContainer.size.width != Self.truncatedWidth {
65 textContainer.size = CGSize(width: Self.truncatedWidth, height: CGFloat.greatestFiniteMagnitude)
66 }
67 super.layoutSubviews()
68 // The text view sizes its content to its own width; truncated lines need the widest
69 // laid-out line's.
70 if truncates, let manager = textLayoutManager {
71 let width = ceil(manager.usageBoundsForTextContainer.maxX + textContainerInset.left + textContainerInset.right)
72 if contentSize.width < width { contentSize.width = width }
73 }
74 onLayout?()
75 }
76
77 override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
78 var rest: Set<UIPress> = []
79 for press in presses {
80 if let key = press.key, keyHandler?(key) == true {
81 handled = (handled ?? []).union([key.keyCode])
82 } else {
83 rest.insert(press)
84 }
85 }
86 if !rest.isEmpty { super.pressesBegan(rest, with: event) }
87 }
88
89 override func pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
90 let rest = presses.filter { press in
91 guard let code = press.key?.keyCode, handled?.contains(code) == true else { return true }
92 handled?.remove(code)
93 return false
94 }
95 if !rest.isEmpty { super.pressesEnded(rest, with: event) }
96 }
97}
98
99/// The iOS editor: a TextKit 2 text view that is the open file's live state, as the Mac's
100/// `OrgEditor` is. Typing and undo go through the text view and into the document; commands
101/// run on the document and apply their edits as one undo step; headings, drawers and blocks
102/// fold as TAB cycles them.
103@MainActor
104final class MobileEditor: NSObject, DocumentBuffer {
105 /// One highlighter for every editor and the reader: it caches compiled grammars and results.
106 static let highlighter = TreeSitterHighlighter()
107 private(set) var document: DocumentState
108 let textView: UITextView
109 var options: EditingOptions = .org {
110 didSet {
111 textView.spellCheckingType = options.spellCheck ? .yes : .no
112 if !showMarkup, options.hideEmphasisMarkers != oldValue.hideEmphasisMarkers || options.prettyEntities != oldValue.prettyEntities {
113 restyleAll()
114 }
115 }
116 }
117 /// Colors and type; a change, or a new Dynamic Type size, restyles the file.
118 var themeSpec: ThemeSpec {
119 get { theme.spec }
120 set {
121 let new = MobileTheme(newValue)
122 guard new.spec != theme.spec || new.font != theme.font else { return }
123 theme = new
124 paragraphStyles = [:]
125 applyThemeToView()
126 restyleAll()
127 }
128 }
129 /// Link brackets and targets, and emphasis markers when `org-hide-emphasis-markers` hides
130 /// them, shown. Hidden markup shows on the caret's line, so it can be edited.
131 var showMarkup = true {
132 didSet { if showMarkup != oldValue { restyleAll() } }
133 }
134 var keymap = KeymapPreset.emacs.keymap
135 var onChange: (() -> Void)?
136 var onMessage: ((String) -> Void)?
137 var onPrompt: ((Prompt, @escaping (String?) -> Void) -> Void)?
138 var onLink: ((OrgLink) -> Void)?
139 /// Edits being applied, which the typing hooks leave alone.
140 private var applyingEdits = false
141 /// Source blocks to write to their files (C-c C-v t).
142 var onTangle: ((Tangle.Scope) -> Void)?
143 /// A source block to run (C-c C-c).
144 var onBabel: ((BabelJob) -> Void)?
145 /// The file's setup files to read again (C-c C-c on a keyword line).
146 var onRefreshSetup: (() -> Void)?
147 /// A block, a table's formulas or a field to edit apart (C-c ', C-c `).
148 var onEditBlock: ((BlockEdit) -> Void)?
149 /// A followed timestamp's agenda days: the first (a `Days` number) and how many.
150 var onAgenda: ((Int, Int) -> Void)?
151 /// Commands the app runs, as `app.clock.in`.
152 var onAppCommand: ((String) -> Void)?
153 /// Tags used across the workspace, for completion.
154 var knownTags: @Sendable () -> [String] = { [] }
155
156 private var theme: MobileTheme
157 private(set) var fold = FoldState()
158 private var globalVisibility: GlobalVisibility?
159 let hidden = LockedRanges()
160 /// Blocks drawn on a band.
161 let shaded = LockedRanges()
162 let fragmentStyle = FragmentStyle()
163 private var selectionColor: UIColor = .clear
164 /// `org-indent-mode` and `org-hide-leading-stars`, from the settings and `#+STARTUP`.
165 private var indented = true
166 private var hideStars = false
167 /// One paragraph style per indent pair.
168 private var paragraphStyles: [[Int]: NSParagraphStyle] = [:]
169 /// The line last revealed while markup is hidden, to hide again when the caret leaves.
170 private var revealedLine: NSRange?
171 /// `org-toggle-inline-images`: lines that are only an image link show the image.
172 private(set) var showsImages = false
173 /// The view width images were last sized for.
174 private var imageWidth: CGFloat = 0
175 /// The file's folder, for relative image paths.
176 let baseDirectory: URL?
177 private static let imageCache = NSCache<NSString, UIImage>()
178 private var loading = false
179 private var restyleScheduled: Range<Int>?
180 /// Narrowed table columns (`org-table-shrink`).
181 private var shrunk = ShrunkColumns()
182 /// A command's edits being applied, which keep shrunk columns narrow.
183 private var commandEditing = false
184
185 init(
186 document: DocumentState, editable: Bool, options: EditingOptions = .org, theme spec: ThemeSpec = .default,
187 showMarkup: Bool = true, baseDirectory: URL? = nil
188 ) {
189 self.document = document
190 self.options = options
191 self.showMarkup = showMarkup
192 self.baseDirectory = baseDirectory
193 theme = MobileTheme(spec)
194 let keyed = KeyedTextView(usingTextLayoutManager: true)
195 textView = keyed
196 super.init()
197 keyed.keyHandler = { [weak self] key in self?.handleKey(key) ?? false }
198 keyed.onLayout = { [weak self] in self?.viewResized() }
199 textView.isEditable = editable
200 textView.autocorrectionType = .no
201 textView.autocapitalizationType = .none
202 textView.smartQuotesType = .no
203 textView.smartDashesType = .no
204 textView.smartInsertDeleteType = .no
205 textView.spellCheckingType = options.spellCheck ? .yes : .no
206 textView.keyboardDismissMode = .interactive
207 textView.alwaysBounceVertical = true
208 textView.textContainerInset = UIEdgeInsets(top: 12, left: 8, bottom: 24, right: 8)
209 textView.delegate = self
210 textView.textStorage.delegate = self
211 textView.textLayoutManager?.delegate = self
212 (textView.textLayoutManager?.textContentManager as? NSTextContentStorage)?.delegate = self
213 let startup = Presentation.startupDisplay(document.tree, options: options)
214 indented = startup.indented
215 hideStars = startup.hideStars
216 showsImages = startup.inlineImages
217 shrunk = ShrunkColumns.startup(document.tree)
218 applyThemeToView()
219 load(document.text)
220 setFolds(startup.folds)
221 if startup.alignTables { _ = perform(AlignAllTables()) }
222 truncatesLines = startup.truncated
223 textView.selectedRange = NSRange(location: 0, length: 0)
224 }
225
226 // MARK: - DocumentBuffer
227
228 var selection: [Range<Int>] {
229 let selected = textView.selectedRange
230 return [selected.location..<NSMaxRange(selected)]
231 }
232
233 func update<T>(_ change: (inout DocumentState) throws -> T) rethrows -> T {
234 let before = document.text
235 let defaultsBefore = document.defaults
236 let selected = textView.selectedRange
237 let result = try change(&document)
238 if document.text != before {
239 // A save that merged a change from disk, or a revert: the view shows the new text.
240 shrunk = ShrunkColumns()
241 load(document.text)
242 let length = (document.text as NSString).length
243 textView.selectedRange = NSRange(location: min(selected.location, length), length: 0)
244 textView.undoManager?.removeAllActions()
245 setFolds(fold)
246 } else if document.defaults != defaultsBefore {
247 restyle(0..<(document.text as NSString).length)
248 }
249 return result
250 }
251
252 func perform(_ command: any OrgCommand, now: Date = Date(), answers: [String: String] = [:]) -> CommandStep {
253 let context = EditContext(
254 revision: document.revision, text: document.text, tree: document.tree, selection: selection,
255 now: now, answers: answers, hidden: hidden.all, options: options, knownTags: knownTags
256 )
257 let step = command.run(in: context)
258 switch step {
259 case .commit(let result):
260 guard textView.isEditable || result.edits.isEmpty else {
261 onMessage?("This file is read-only.")
262 return .failed("read-only")
263 }
264 commandEditing = true
265 applyEdits(result.edits)
266 commandEditing = false
267 if let selected = result.selection?.first {
268 unfold(around: selected.lowerBound)
269 textView.selectedRange = NSRange(location: selected.lowerBound, length: selected.count)
270 textView.scrollRangeToVisible(textView.selectedRange)
271 }
272 for effect in result.effects {
273 switch effect {
274 case .message(let text): onMessage?(text)
275 case .fold(let start):
276 var state = fold
277 state.folds.insert(start)
278 setFolds(state)
279 case .refreshSetup: onRefreshSetup?()
280 default: break
281 }
282 }
283 case .failed(let message):
284 onMessage?(message)
285 case .prompt(let prompt):
286 onPrompt?(prompt) { [weak self] answer in
287 guard let self else { return }
288 guard let answer else { return self.onMessage?("Quit") ?? () }
289 _ = self.perform(command, now: now, answers: answers.merging([prompt.key: answer]) { $1 })
290 }
291 case .external(.editBlock(let edit)) where onEditBlock != nil:
292 onEditBlock?(edit)
293 case .external(.babel(let job)) where onBabel != nil:
294 onBabel?(job)
295 case .external(.tangle(let scope)) where onTangle != nil:
296 onTangle?(scope)
297 case .external(.agenda(let start, let count)) where onAgenda != nil:
298 onAgenda?(start, count)
299 case .external(let request):
300 onMessage?(Self.unavailable(request, title: command.title))
301 }
302 return step
303 }
304
305 /// Why a request the app doesn't handle did nothing: only table recalculation needs Emacs.
306 static func unavailable(_ request: ExternalRequest, title: String) -> String {
307 if case .emacsTable(_, _, _, let reason, _) = request { return "This table needs Emacs, which runs on the Mac: \(reason)." }
308 return "\(title) isn't available on iPhone and iPad."
309 }
310
311 // MARK: - Commands by name and key
312
313 /// Runs what `keys` (as `C-c C-t`) is bound to in the Emacs keymap, for the caret's context.
314 func run(keys: String) {
315 guard let chords = KeySequence.parse(keys) else { return }
316 let context = editContext()
317 let binding = keymap.candidates(for: chords).first { binding in
318 (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
319 }
320 guard let binding else { return onMessage?("Nothing to do here") ?? () }
321 run(binding.command)
322 }
323
324 func run(_ id: String) {
325 switch id {
326 case "org.cycle":
327 if !cycleAtCaret() { onMessage?("Not on a heading, drawer or block") }
328 case "org.cycle-global": cycleGlobal()
329 case "org.link.open": openLinkAtCaret()
330 case "org.toggle-inline-images": toggleImages()
331 case "editor.toggle-truncate-lines":
332 truncatesLines.toggle()
333 onMessage?(truncatesLines ? "Truncate long lines enabled" : "Truncate long lines disabled")
334 case "edit.undo": textView.undoManager?.undo()
335 case "edit.redo": textView.undoManager?.redo()
336 case "org.table.toggle-column-width", "org.table.shrink", "org.table.expand": tableColumnWidth(id)
337 case _ where id.hasPrefix("app.") || Self.linkCommands.contains(id):
338 if let onAppCommand { onAppCommand(id) } else { onMessage?("Not available on iOS yet") }
339 default:
340 if let command = Commands.command(id) {
341 _ = perform(command)
342 } else {
343 onMessage?("Not available on iOS yet")
344 }
345 }
346 }
347
348 /// Link commands that need the stored links or the file, which the screen has.
349 static let linkCommands: Set<String> = ["org.link.store", "org.id.store-link", "org.link.insert"]
350
351 func applies(_ id: String, in context: EditContext) -> Bool {
352 if let command = Commands.command(id) { return command.applies(in: context) }
353 switch id {
354 case "org.cycle":
355 return Presentation.heading(containing: context.caret, in: context.tree) != nil || Wrappers.toggleable(at: context.caret, in: context.tree) != nil
356 case "org.cycle-global", "edit.undo", "edit.redo", "org.toggle-inline-images", "editor.toggle-truncate-lines": return true
357 case "app.clock.in", "app.clock.out", "app.clock.cancel", "app.clock.goto", "app.clock.in-recent", "app.clock.in-last",
358 "app.clock.goto-recent", "app.clock.default", "app.clock.resolve", "app.toggle-markup": return onAppCommand != nil
359 case _ where Self.linkCommands.contains(id): return onAppCommand != nil
360 case "org.link.open": return OpenLinkAtPoint().applies(in: context)
361 case "org.table.toggle-column-width", "org.table.shrink", "org.table.expand":
362 return TableShrink.table(at: context.caret, in: context.text) != nil
363 default: return false
364 }
365 }
366
367 // MARK: - Hardware keyboard
368
369 private lazy var dispatcher = KeyDispatcher(keymap: keymap)
370
371 private static let named: [UIKeyboardHIDUsage: String] = [
372 .keyboardTab: "TAB", .keyboardReturnOrEnter: "RET", .keypadEnter: "RET", .keyboardSpacebar: "SPC",
373 .keyboardEscape: "ESC", .keyboardDeleteOrBackspace: "DEL", .keyboardDeleteForward: "<delete>",
374 .keyboardLeftArrow: "<left>", .keyboardRightArrow: "<right>", .keyboardUpArrow: "<up>", .keyboardDownArrow: "<down>",
375 .keyboardHome: "<home>", .keyboardEnd: "<end>", .keyboardPageUp: "<prior>", .keyboardPageDown: "<next>",
376 ]
377
378 /// A key press as a chord; Option is Meta, as `option-as-meta` makes it on the Mac.
379 static func chord(_ key: UIKey) -> KeyChord? {
380 var modifiers: KeyChord.Modifiers = []
381 let flags = key.modifierFlags
382 if flags.contains(.control) { modifiers.insert(.control) }
383 if flags.contains(.alternate) { modifiers.insert(.meta) }
384 if flags.contains(.command) { modifiers.insert(.command) }
385 if let name = named[key.keyCode] {
386 if flags.contains(.shift) { modifiers.insert(.shift) }
387 return KeyChord(name, modifiers)
388 }
389 var characters = key.charactersIgnoringModifiers
390 if flags.contains(.shift), characters.count == 1, characters.lowercased() == characters { characters = characters.uppercased() }
391 guard characters.count == 1 else { return nil }
392 return KeyChord(characters, modifiers)
393 }
394
395 /// The Emacs keymap's commands on an iPad keyboard. Keys it doesn't bind, Command shortcuts
396 /// and editing keys (C-a, C-e, C-k...) are the text system's.
397 func handleKey(_ key: UIKey) -> Bool {
398 guard let chord = Self.chord(key), !chord.modifiers.contains(.command) else { return false }
399 // Option alone types characters unless it begins a binding.
400 if chord.modifiers == [.meta], dispatcher.pending.isEmpty,
401 keymap.candidates(for: [chord]).isEmpty, !keymap.isPrefix([chord]) { return false }
402 switch dispatcher.feed(chord) {
403 case .pending(let keys):
404 onMessage?(KeySequence.format(keys) + "-")
405 return true
406 case .cancelled:
407 onMessage?("Quit")
408 return true
409 case .undefined(let keys):
410 onMessage?("\(KeySequence.format(keys)) is undefined")
411 return true
412 case .unbound:
413 return false
414 case .complete(let keys, let candidates):
415 let context = editContext()
416 let runnable = candidates.first { binding in
417 (binding.when.map { KeyContext.holds($0, in: context) } ?? true) && applies(binding.command, in: context)
418 }
419 // A sequence runs its command even where it doesn't apply, which says why, as on the Mac.
420 guard let binding = runnable ?? (keys.count > 1 ? candidates.first : nil) else { return false }
421 if keys.count == 1, binding.command.hasPrefix("edit."), !["edit.undo", "edit.redo"].contains(binding.command) { return false }
422 run(binding.command)
423 return true
424 }
425 }
426
427 func editContext() -> EditContext {
428 EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: selection, hidden: hidden.all, options: options, knownTags: knownTags)
429 }
430
431 private func openLinkAtCaret() {
432 let caret = textView.selectedRange.location
433 if let link = Links.link(at: caret, text: document.text, tree: document.tree)?.link {
434 onLink?(link)
435 } else if let days = Links.timestampDays(at: caret, text: document.text) {
436 onAgenda?(days.start, days.count)
437 } else {
438 onMessage?("No link here")
439 }
440 }
441
442 // MARK: - Editing
443
444 /// Applies `edits` (against the current text) through the text view as one undo step.
445 func applyEdits(_ edits: [TextEdit]) {
446 let interval = Perf.begin("editor.applyEdits")
447 defer { interval.end() }
448 guard !edits.isEmpty else { return }
449 applyingEdits = true
450 defer { applyingEdits = false }
451 // Straight into the storage: replacing through text input would take the active
452 // keyboard's substitutions (smart dashes) when another view has the keyboard.
453 let storage = textView.textStorage
454 let old = storage.string as NSString
455 // By lines, so a fold between two changes stays.
456 let ascending = edits.flatMap { splitByLines($0, in: storage.string) }.sorted { $0.range.lowerBound < $1.range.lowerBound }
457 var inverse: [TextEdit] = []
458 var delta = 0
459 for edit in ascending {
460 let start = edit.range.lowerBound + delta
461 let length = (edit.replacement as NSString).length
462 inverse.append(TextEdit(range: start..<start + length, replacement: old.substring(with: NSRange(edit.range))))
463 delta += length - edit.range.count
464 }
465 let caret = textView.selectedRange
466 // One at a time, last first: each is processed alone, so folds between them stay.
467 for edit in ascending.reversed() {
468 storage.replaceCharacters(in: NSRange(edit.range), with: edit.replacement)
469 }
470 textView.undoManager?.registerUndo(withTarget: self) { editor in
471 editor.applyEdits(inverse)
472 editor.textView.selectedRange = caret
473 }
474 }
475
476 /// The storage changed (typing, a command, undo): the document takes the same edit, and
477 /// folds and styles follow.
478 fileprivate func storageEdited(range: NSRange, delta: Int) {
479 let interval = Perf.begin("editor.edit")
480 defer { interval.end() }
481 guard !loading else { return }
482 let old = range.location..<(range.location + range.length - delta)
483 let replacement = (textView.textStorage.string as NSString).substring(with: range)
484 let edit = TextEdit(range: old, replacement: replacement)
485 do {
486 try document.apply([edit], baseRevision: document.revision)
487 } catch {
488 // Out of step: the view's text wins.
489 shrunk = ShrunkColumns()
490 load(textView.textStorage.string)
491 return
492 }
493 for table in shrunk.map(through: edit, in: textView.textStorage.string, command: commandEditing) { scheduleRestyle(table) }
494 fold = FoldState(
495 folds: Self.map(fold.folds, old, delta), bodyFolds: Self.map(fold.bodyFolds, old, delta),
496 wrapperFolds: Self.map(fold.wrapperFolds, old, delta)
497 )
498 scheduleRestyle(range.location..<NSMaxRange(range))
499 onChange?()
500 }
501
502 /// Starts after the edit move with it; ones inside it go.
503 private static func map(_ starts: Set<Int>, _ old: Range<Int>, _ delta: Int) -> Set<Int> {
504 Set(starts.compactMap { start in
505 if start >= old.upperBound { return start + delta }
506 return start <= old.lowerBound ? start : nil
507 })
508 }
509
510 // MARK: - Styling
511
512 private func load(_ text: String) {
513 loading = true
514 textView.textStorage.setAttributedString(NSAttributedString(string: text, attributes: theme.base))
515 loading = false
516 shaded.set(Presentation.shadedBlocks(document.tree), folded: [])
517 restyle(0..<(text as NSString).length)
518 textView.typingAttributes = theme.base
519 }
520
521 /// The text view's own colors, and the block band's.
522 private func applyThemeToView() {
523 textView.backgroundColor = theme.color("background") ?? .systemBackground
524 textView.tintColor = theme.color("cursor")
525 textView.typingAttributes = theme.base
526 fragmentStyle.set(blockBackground: theme.color("block-background") ?? .clear, width: textView.bounds.width)
527 themeSelection()
528 }
529
530 /// The selection in the theme's selection color: the text view's selection display
531 /// interaction draws it with our highlight view; the cursor and handles keep the tint.
532 private func themeSelection() {
533 guard let interaction = textView.interactions.lazy.compactMap({ $0 as? UITextSelectionDisplayInteraction }).first else { return }
534 let view = interaction.highlightView as? SelectionHighlightView ?? SelectionHighlightView()
535 view.color = theme.color("selection") ?? UIColor.tintColor.withAlphaComponent(0.25)
536 if interaction.highlightView !== view { interaction.highlightView = view }
537 selectionColor = view.color
538 }
539
540 /// The highlight view draws under the text, so a block's band would cover it: blocks the
541 /// selection enters or leaves are laid out again to draw it over their band.
542 private func redrawSelectedBlocks() {
543 let selected = textView.selectedRange
544 let range = selected.length > 0 ? selected.location..<NSMaxRange(selected) : nil
545 let old = fragmentStyle.selection?.range
546 fragmentStyle.set(selection: range, color: selectionColor)
547 guard let manager = textView.textLayoutManager, let content = manager.textContentManager else { return }
548 let touched = [old, range].compactMap { $0 }
549 for block in shaded.all where touched.contains(where: { $0.overlaps(block) }) {
550 guard let start = content.location(content.documentRange.location, offsetBy: block.lowerBound),
551 let end = content.location(start, offsetBy: block.count),
552 let textRange = NSTextRange(location: start, end: end) else { continue }
553 // Fragments are kept across layout passes, so they are asked to draw again too.
554 manager.invalidateRenderingAttributes(for: textRange)
555 manager.invalidateLayout(for: textRange)
556 }
557 textView.setNeedsDisplay()
558 }
559
560 /// The band behind blocks spans the view's width, or the widest line's when truncated;
561 /// images are as wide as the view allows.
562 private func viewResized() {
563 let band = fragmentStyle.blockBand
564 let width = max(textView.bounds.width, truncatesLines ? textView.contentSize.width : 0)
565 let resized = imageWidth != textView.bounds.width
566 guard band.width != width || resized else { return }
567 fragmentStyle.set(blockBackground: band.color, width: width)
568 imageWidth = textView.bounds.width
569 if showsImages, resized { restyle(0..<textView.textStorage.length) }
570 if let manager = textView.textLayoutManager {
571 manager.invalidateRenderingAttributes(for: manager.documentRange)
572 manager.invalidateLayout(for: manager.documentRange)
573 }
574 }
575
576 /// Styles the whole file again.
577 private func restyleAll() {
578 let interval = Perf.begin("editor.restyleAll")
579 defer { interval.end() }
580 restyle(0..<textView.textStorage.length)
581 if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) }
582 }
583
584 /// Styles are set after the edit has been processed, as TextKit asks.
585 private func scheduleRestyle(_ range: Range<Int>) {
586 if let pending = restyleScheduled {
587 restyleScheduled = min(pending.lowerBound, range.lowerBound)..<max(pending.upperBound, range.upperBound)
588 return
589 }
590 restyleScheduled = range
591 DispatchQueue.main.async { [weak self] in
592 guard let self, let range = self.restyleScheduled else { return }
593 self.restyleScheduled = nil
594 self.shaded.set(Presentation.shadedBlocks(self.document.tree), folded: [])
595 // Small files are restyled whole: a heading or block line changes what follows it.
596 let length = self.textView.textStorage.length
597 self.restyle(length < 60_000 ? 0..<length : range)
598 self.updateHidden()
599 self.textView.typingAttributes = self.theme.base
600 }
601 }
602
603 private var caretLine: NSRange {
604 let text = textView.textStorage.string as NSString
605 return text.lineRange(for: NSRange(location: min(textView.selectedRange.location, text.length), length: 0))
606 }
607
608 /// Sets attributes for the whole lines in `range`, as the Mac editor does.
609 private func restyle(_ range: Range<Int>) {
610 let interval = Perf.begin("editor.restyle")
611 defer { interval.end() }
612 let storage = textView.textStorage
613 let ns = storage.string as NSString
614 guard ns.length > 0 else { return }
615 let lower = min(range.lowerBound, ns.length)
616 let lines = ns.lineRange(for: NSRange(location: lower, length: min(range.count, ns.length - lower)))
617 let whole = lines.location..<NSMaxRange(lines)
618 storage.beginEditing()
619 storage.setAttributes(theme.base, range: lines)
620 if indented {
621 for line in Presentation.lineIndents(document.tree, in: whole) {
622 storage.addAttribute(.paragraphStyle, value: paragraphStyle(line.firstLine, line.wrapped), range: NSRange(line.range))
623 }
624 }
625 let revealed = caretLine
626 var scriptExclusions: [Range<Int>] = []
627 for run in Presentation.styles(document.tree, in: whole, highlighter: Self.highlighter) {
628 let clipped = NSIntersectionRange(NSRange(run.range), lines)
629 guard clipped.length > 0 else { continue }
630 if Presentation.skipsLeadingStars(run.role, indented: indented, hideStars: hideStars) { continue }
631 if !showMarkup, Presentation.hidesWithMarkup(run.role, options: options), NSIntersectionRange(clipped, revealed).length == 0 {
632 storage.addAttributes(theme.hidden, range: clipped)
633 } else {
634 theme.apply(run.role, to: storage, range: clipped)
635 }
636 if Presentation.excludesScripts(run.role) { scriptExclusions.append(run.range) }
637 }
638 if !showMarkup, options.prettyEntities { prettify(whole, in: storage, revealed: revealed, scriptExclusions: scriptExclusions) }
639 applyShrunk(whole, in: storage)
640 applyImages(whole, in: storage, revealed: revealed)
641 storage.endEditing()
642 }
643
644 private func paragraphStyle(_ firstLine: Int, _ wrapped: Int) -> NSParagraphStyle {
645 if let style = paragraphStyles[[firstLine, wrapped]] { return style }
646 let style = theme.paragraphStyle(firstLine: firstLine, wrapped: wrapped)
647 paragraphStyles[[firstLine, wrapped]] = style
648 return style
649 }
650
651 /// `org-pretty-entities`: entities drawn as their character over the entity's last
652 /// character (the rest hidden), sub/superscripts raised without their markers.
653 private func prettify(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange, scriptExclusions: [Range<Int>]) {
654 let runs = Presentation.prettyRuns(
655 storage.string as NSString, in: range, revealedLine: revealed.location, inBlock: { shaded.containing($0) != nil },
656 scriptExclusions: scriptExclusions, subSuperscriptsNeedBraces: options.subSuperscriptsNeedBraces
657 )
658 for (lineStart, run) in runs {
659 switch run {
660 case .entity(let r, let display):
661 let start = lineStart + r.lowerBound
662 let last = lineStart + r.upperBound - 1
663 let color = storage.attribute(.foregroundColor, at: last, effectiveRange: nil) as? UIColor ?? theme.foreground
664 if last > start { storage.addAttributes(theme.hidden, range: NSRange(location: start, length: last - start)) }
665 storage.addAttributes([.foregroundColor: UIColor.clear, .orgEntityDisplay: display, .orgEntityColor: color], range: NSRange(location: last, length: 1))
666 case .script(let markers, let body, let superscript):
667 for marker in markers {
668 storage.addAttributes(theme.hidden, range: NSRange(location: lineStart + marker.lowerBound, length: marker.count))
669 }
670 let size = theme.font.pointSize
671 storage.addAttributes([
672 .font: theme.font.withSize(size * 0.7),
673 .baselineOffset: (superscript ? 0.3 : -0.3) * size,
674 ], range: NSRange(location: lineStart + body.lowerBound, length: body.count))
675 }
676 }
677 }
678
679 /// Moving to another line shows its markup and hides the last one's.
680 private func revealCaretLine() {
681 guard !showMarkup else { return }
682 let line = caretLine
683 guard line != revealedLine else { return }
684 let text = textView.textStorage.string as NSString
685 // The old line may have moved with edits since; restyle the line now at its start.
686 let old = revealedLine.flatMap { $0.location <= text.length ? text.lineRange(for: NSRange(location: $0.location, length: 0)) : nil }
687 revealedLine = line
688 for range in [old, line].compactMap({ $0 }) {
689 restyle(range.location..<NSMaxRange(range))
690 }
691 }
692
693 // MARK: - Shrunk table columns
694
695 /// C-c TAB in a table: `org-table-toggle-column-width`; `shrink` for `org-table-shrink`,
696 /// `expand` for `org-table-expand`.
697 private func tableColumnWidth(_ id: String) {
698 switch shrunk.change(for: id, at: textView.selectedRange.location, in: textView.textStorage.string) {
699 case .notInTable: onMessage?("Not in a table")
700 case .set(let columns, let table): setShrunk(columns, in: table)
701 case .ask(let table, let current, let max):
702 onPrompt?(Prompt(key: "columns", message: "Column ranges (e.g. 2-4 6-):")) { [weak self] answer in
703 guard let self, let answer else { return }
704 self.setShrunk(ShrunkColumns.toggled(current, TableShrink.columns(answer, max: max)), in: table)
705 }
706 }
707 }
708
709 /// Narrows `columns` of `table` and widens its others.
710 private func setShrunk(_ columns: [Int], in table: Range<Int>) {
711 shrunk.set(columns, in: table, text: textView.textStorage.string)
712 restyleAll()
713 }
714
715 /// Hides each shrunk segment's text and draws its display where the text was, as pretty
716 /// entities draw theirs.
717 private func applyShrunk(_ range: Range<Int>, in storage: NSTextStorage) {
718 guard !shrunk.isEmpty else { return }
719 let cell = theme.column
720 for segment in shrunk.segments where segment.range.overlaps(range) && segment.range.upperBound <= storage.length {
721 let r = segment.range
722 let shown = segment.display.count
723 let kept = min(shown, r.count)
724 if r.count > kept { storage.addAttributes(theme.hidden, range: NSRange(location: r.lowerBound, length: r.count - kept)) }
725 guard kept > 0 else { continue }
726 let visible = NSRange(location: r.upperBound - kept, length: kept)
727 let color = storage.attribute(.foregroundColor, at: visible.location, effectiveRange: nil) as? UIColor ?? theme.foreground
728 storage.addAttribute(.foregroundColor, value: UIColor.clear, range: visible)
729 storage.addAttributes([.orgEntityDisplay: segment.display, .orgEntityColor: color], range: NSRange(location: visible.location, length: 1))
730 if shown > kept { storage.addAttribute(.kern, value: CGFloat(shown - kept) * cell, range: NSRange(location: NSMaxRange(visible) - 1, length: 1)) }
731 }
732 }
733
734 // MARK: - Inline images
735
736 private func toggleImages() {
737 showsImages.toggle()
738 restyleAll()
739 if showsImages {
740 let ns = textView.textStorage.string as NSString
741 var count = 0
742 var offset = 0
743 while offset < ns.length {
744 let line = ns.lineRange(for: NSRange(location: offset, length: 0))
745 if let image = InlineImages.image(atLine: line.location, in: ns), Self.loadImage(image.path, relativeTo: baseDirectory) != nil { count += 1 }
746 offset = NSMaxRange(line)
747 }
748 onMessage?("\(count) images displayed inline")
749 } else {
750 onMessage?("Inline image display turned off")
751 }
752 }
753
754 /// An image link's image, by its path or one relative to `baseDirectory`.
755 static func loadImage(_ path: String, relativeTo baseDirectory: URL?) -> UIImage? {
756 let expanded = (path as NSString).expandingTildeInPath
757 let url: URL
758 if expanded.hasPrefix("/") {
759 url = URL(fileURLWithPath: expanded)
760 } else if let baseDirectory {
761 url = baseDirectory.appendingPathComponent(expanded)
762 } else {
763 return nil
764 }
765 let modified = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate?.timeIntervalSince1970 ?? 0
766 let key = "\(url.path)|\(modified)" as NSString
767 if let cached = Self.imageCache.object(forKey: key) { return cached }
768 guard let image = UIImage(contentsOfFile: url.path) else { return nil }
769 Self.imageCache.setObject(image, forKey: key)
770 return image
771 }
772
773 /// Image lines in `range` show the image over the link, which is hidden unless the caret is
774 /// on the line.
775 private func applyImages(_ range: Range<Int>, in storage: NSTextStorage, revealed: NSRange) {
776 guard showsImages else { return }
777 let text = storage.string as NSString
778 let inset = textView.textContainerInset
779 let maxWidth = max(80, textView.bounds.width - inset.left - inset.right - 40)
780 var location = range.lowerBound
781 while location < range.upperBound, location < text.length {
782 let line = text.lineRange(for: NSRange(location: location, length: 0))
783 location = NSMaxRange(line)
784 guard let image = InlineImages.image(atLine: line.location, in: text), let picture = Self.loadImage(image.path, relativeTo: baseDirectory) else { continue }
785 let width = min(image.width.map(CGFloat.init) ?? picture.size.width, maxWidth)
786 let height = picture.size.width > 0 ? width * picture.size.height / picture.size.width : 0
787 let content = NSRange(location: line.location, length: line.length - (text.substring(with: line).hasSuffix("\n") ? 1 : 0))
788 // Invisible, keeping the line's height.
789 if line.location != revealed.location, content.length > 0 {
790 storage.addAttributes([.foregroundColor: UIColor.clear, .underlineStyle: 0], range: content)
791 }
792 storage.addAttribute(.orgImage, value: InlineImageBox(image: picture, size: CGSize(width: width, height: height)), range: NSRange(location: line.location, length: max(1, content.length)))
793 let style = (storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle ?? NSMutableParagraphStyle()
794 // The image sits where the line is; the spacing makes room for the rest of it.
795 style.paragraphSpacing = max(0, height + 4 - theme.font.lineHeight)
796 storage.addAttribute(.paragraphStyle, value: style, range: line)
797 }
798 }
799
800 // MARK: - Truncation
801
802 /// `toggle-truncate-lines`: long lines run off the right edge, scrolling sideways, instead
803 /// of wrapping.
804 var truncatesLines: Bool {
805 get { (textView as? KeyedTextView)?.truncates ?? false }
806 set {
807 guard newValue != truncatesLines, let view = textView as? KeyedTextView else { return }
808 view.truncates = newValue
809 if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) }
810 }
811 }
812
813 // MARK: - Folding
814
815 func setFolds(_ state: FoldState) {
816 fold = state
817 updateHidden()
818 }
819
820 private func updateHidden() {
821 let tree = document.tree
822 let wrappers = fold.wrapperFolds.compactMap { Wrappers.starting(at: $0, in: tree)?.hidden }
823 hidden.set(
824 Presentation.hiddenRanges(tree, folds: fold.folds, bodyFolds: fold.bodyFolds, wrapperRanges: wrappers),
825 folded: fold.folds.union(fold.bodyFolds).union(fold.wrapperFolds)
826 )
827 if let manager = textView.textLayoutManager { manager.invalidateLayout(for: manager.documentRange) }
828 textView.setNeedsDisplay()
829 }
830
831 /// TAB at the caret: a heading cycles, a drawer or block opens or closes.
832 @discardableResult
833 func cycleAtCaret() -> Bool {
834 guard let next = Presentation.cycle(at: textView.selectedRange.location, in: document.tree, fold) else { return false }
835 setFolds(next)
836 return true
837 }
838
839 /// Shift-TAB: overview, contents, show all.
840 func cycleGlobal() {
841 let (visibility, state) = Presentation.cycleGlobal(from: globalVisibility, in: document.tree, wrapperFolds: fold.wrapperFolds)
842 globalVisibility = visibility
843 setFolds(state)
844 }
845
846 /// Opens the folds hiding `offset`.
847 func unfold(around offset: Int) {
848 var state = fold
849 for entry in Presentation.outline(document.tree) where entry.start < offset && offset < entry.end {
850 state.folds.remove(entry.start)
851 state.bodyFolds.remove(entry.start)
852 }
853 for start in state.wrapperFolds where Wrappers.starting(at: start, in: document.tree)?.hidden.contains(offset) == true {
854 state.wrapperFolds.remove(start)
855 }
856 if state != fold { setFolds(state) }
857 }
858
859 /// Shows the heading at `offset`, unfolded, at the top.
860 func reveal(_ offset: Int) {
861 let length = textView.textStorage.length
862 let target = min(max(0, offset), length)
863 unfold(around: target)
864 textView.selectedRange = NSRange(location: target, length: 0)
865 textView.scrollRangeToVisible(NSRange(location: target, length: 0))
866 }
867
868 /// The caret left hidden text (a tap past a fold): what hides it opens.
869 fileprivate func selectionChanged() {
870 let interval = Perf.begin("editor.selection")
871 defer { interval.end() }
872 redrawSelectedBlocks()
873 let caret = textView.selectedRange.location
874 if hidden.containing(caret) != nil { unfold(around: caret) }
875 revealCaretLine()
876 }
877}
878
879extension MobileEditor: UITextViewDelegate {
880 func textViewDidChangeSelection(_ textView: UITextView) {
881 selectionChanged()
882 }
883
884 /// `electric-pair-mode` for typed brackets and quotes, DEL and RET, from either keyboard.
885 func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
886 guard options.electricPair, !applyingEdits, textView.markedTextRange == nil else { return true }
887 let selected = textView.selectedRange
888 let key: String
889 if text.isEmpty, selected.length == 0, range.length == 1, NSMaxRange(range) == selected.location {
890 key = "DEL"
891 } else if range == selected, text == "\n" {
892 key = "RET"
893 } else if range == selected, ElectricPairKey.characters.contains(text) {
894 key = text
895 } else {
896 return true
897 }
898 let command = ElectricPairKey(key: key)
899 guard command.applies(in: editContext()) else { return true }
900 _ = perform(command)
901 return false
902 }
903}
904
905extension MobileEditor: NSTextStorageDelegate {
906 nonisolated func textStorage(
907 _ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorage.EditActions, range editedRange: NSRange, changeInLength delta: Int
908 ) {
909 guard editedMask.contains(.editedCharacters) else { return }
910 MainActor.assumeIsolated { storageEdited(range: editedRange, delta: delta) }
911 }
912}
913
914extension MobileEditor: NSTextContentStorageDelegate {
915 /// Folded text isn't enumerated, so it isn't laid out or drawn.
916 nonisolated func textContentManager(
917 _ textContentManager: NSTextContentManager, shouldEnumerate textElement: NSTextElement, options: NSTextContentManager.EnumerationOptions = []
918 ) -> Bool {
919 guard let range = textElement.elementRange else { return true }
920 let documentStart = textContentManager.documentRange.location
921 let start = textContentManager.offset(from: documentStart, to: range.location)
922 let end = textContentManager.offset(from: documentStart, to: range.endLocation)
923 return !hidden.covers(start, end)
924 }
925}
926
927extension MobileEditor: NSTextLayoutManagerDelegate {
928 /// Folded headings, drawers and blocks end with `…`; blocks are on a band; image lines
929 /// show their image; pretty entities draw their character.
930 nonisolated func textLayoutManager(
931 _ textLayoutManager: NSTextLayoutManager, textLayoutFragmentFor location: NSTextLocation, in textElement: NSTextElement
932 ) -> NSTextLayoutFragment {
933 let range = textElement.elementRange
934 guard let range, let manager = textLayoutManager.textContentManager else { return NSTextLayoutFragment(textElement: textElement, range: range) }
935 let offset = manager.offset(from: manager.documentRange.location, to: range.location)
936 let folded = hidden.isFolded(offset)
937 let band = shaded.containing(offset) != nil ? fragmentStyle.blockBand : nil
938 let string = (textElement as? NSTextParagraph)?.attributedString
939 let image = string.flatMap(OrgLineFragment.image)
940 let entities = string.map(OrgLineFragment.hasEntities) ?? false
941 guard folded || band != nil || image != nil || entities else { return NSTextLayoutFragment(textElement: textElement, range: range) }
942 let fragment = OrgLineFragment(textElement: textElement, range: range)
943 fragment.folded = folded
944 fragment.band = band
945 if band != nil {
946 fragment.start = offset
947 fragment.style = fragmentStyle
948 }
949 fragment.image = image
950 return fragment
951 }
952}
953
954extension NSAttributedString.Key {
955 /// The character an entity shows as, on the entity's last character.
956 static let orgEntityDisplay = NSAttributedString.Key("OrgEntityDisplay")
957 /// The color the entity's character is drawn in.
958 static let orgEntityColor = NSAttributedString.Key("OrgEntityColor")
959 /// The image an image link's line shows under it.
960 static let orgImage = NSAttributedString.Key("OrgImage")
961}
962
963final class InlineImageBox: NSObject, @unchecked Sendable {
964 let image: UIImage
965 let size: CGSize
966 init(image: UIImage, size: CGSize) {
967 self.image = image
968 self.size = size
969 }
970}
971
972/// Selected text's background, in one color however the rects overlap.
973final class SelectionHighlightView: UIView, UITextSelectionHighlightView {
974 var selectionRects: [UITextSelectionRect] = [] { didSet { setNeedsDisplay() } }
975 var color: UIColor = .clear { didSet { setNeedsDisplay() } }
976
977 override init(frame: CGRect) {
978 super.init(frame: frame)
979 isOpaque = false
980 backgroundColor = .clear
981 isUserInteractionEnabled = false
982 registerForTraitChanges([UITraitUserInterfaceStyle.self]) { (view: SelectionHighlightView, _) in view.setNeedsDisplay() }
983 }
984
985 required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }
986
987 override func draw(_ rect: CGRect) {
988 let path = UIBezierPath()
989 for selection in selectionRects where !selection.rect.isEmpty { path.append(UIBezierPath(rect: selection.rect)) }
990 color.setFill()
991 path.fill()
992 }
993}
994
995/// A line drawn with more than its text, as the Mac editor's fragments draw them: a folded
996/// line's ellipsis, a block's band across the view, an image under an image link, and pretty
997/// entities' characters where the entities' last (invisible) characters sit.
998final class OrgLineFragment: NSTextLayoutFragment, @unchecked Sendable {
999 var folded = false
1000 var band: (color: UIColor, width: CGFloat)?
1001 var image: InlineImageBox?
1002 /// For a block's lines: where the fragment starts, and where the selection is read.
1003 var start = 0
1004 var style: FragmentStyle?
1005
1006 static func image(_ string: NSAttributedString) -> InlineImageBox? {
1007 var found: InlineImageBox?
1008 string.enumerateAttribute(.orgImage, in: NSRange(location: 0, length: string.length)) { value, _, stop in
1009 if let box = value as? InlineImageBox { found = box; stop.pointee = true }
1010 }
1011 return found
1012 }
1013
1014 static func hasEntities(_ string: NSAttributedString) -> Bool {
1015 var found = false
1016 string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, _, stop in
1017 if value != nil { found = true; stop.pointee = true }
1018 }
1019 return found
1020 }
1021
1022 private var bandRect: CGRect? {
1023 guard let band else { return nil }
1024 // Not under the empty line TextKit adds after a final newline.
1025 let height = textLineFragments.last { $0.characterRange.length > 0 }?.typographicBounds.maxY ?? layoutFragmentFrame.height
1026 // The width as it is now: the view may have been laid out since this fragment was made.
1027 let width = style?.blockBand.width ?? band.width
1028 return CGRect(x: -layoutFragmentFrame.minX, y: 0, width: max(width, layoutFragmentFrame.maxX), height: height)
1029 }
1030
1031 private var imageRect: CGRect? {
1032 guard let image, let line = textLineFragments.first else { return nil }
1033 return CGRect(x: line.typographicBounds.minX, y: line.typographicBounds.minY + 2, width: image.size.width, height: image.size.height)
1034 }
1035
1036 override var renderingSurfaceBounds: CGRect {
1037 var bounds = super.renderingSurfaceBounds
1038 if folded { bounds = bounds.insetBy(dx: -40, dy: 0).offsetBy(dx: 40, dy: 0) }
1039 for rect in [bandRect, imageRect].compactMap({ $0 }) { bounds = bounds.union(rect) }
1040 return bounds
1041 }
1042
1043 override func draw(at point: CGPoint, in context: CGContext) {
1044 if let band, let rect = bandRect {
1045 context.saveGState()
1046 context.setFillColor(band.color.cgColor)
1047 context.fill(rect.offsetBy(dx: point.x, dy: point.y))
1048 context.restoreGState()
1049 drawSelection(at: point, in: context, bandRect: rect)
1050 }
1051 super.draw(at: point, in: context)
1052 UIGraphicsPushContext(context)
1053 defer { UIGraphicsPopContext() }
1054 drawEntities(at: point)
1055 if let image, let rect = imageRect { image.image.draw(in: rect.offsetBy(dx: point.x, dy: point.y)) }
1056 if folded, let line = textLineFragments.first(where: { $0.characterRange.length > 0 }) ?? textLineFragments.first {
1057 let bounds = line.typographicBounds
1058 let ellipsis = NSAttributedString(string: " …", attributes: [
1059 .font: UIFont.monospacedSystemFont(ofSize: UIFont.systemFontSize, weight: .regular),
1060 .foregroundColor: UIColor.secondaryLabel,
1061 ])
1062 ellipsis.draw(at: CGPoint(x: point.x + bounds.maxX, y: point.y + bounds.minY))
1063 }
1064 }
1065
1066 /// The selected part of each line, over the band; a selection running past a line's end
1067 /// fills to the band's edge.
1068 private func drawSelection(at point: CGPoint, in context: CGContext, bandRect: CGRect) {
1069 guard let selection = style?.selection else { return }
1070 context.saveGState()
1071 context.setFillColor(selection.color.cgColor)
1072 for line in textLineFragments where line.characterRange.length > 0 {
1073 let lineStart = start + line.characterRange.location
1074 let lineEnd = lineStart + line.characterRange.length
1075 let from = max(selection.range.lowerBound, lineStart), to = min(selection.range.upperBound, lineEnd)
1076 guard from < to || (from == to && selection.range.upperBound > lineEnd && from == lineEnd) else { continue }
1077 let bounds = line.typographicBounds
1078 // From the margin when the selection began on an earlier line, as the system draws it.
1079 let margin = bandRect.minX + (textLayoutManager?.textContainer?.lineFragmentPadding ?? 0)
1080 let x1 = selection.range.lowerBound < lineStart ? margin : bounds.minX + line.locationForCharacter(at: from - start).x
1081 let x2 = selection.range.upperBound >= lineEnd ? bandRect.maxX : bounds.minX + line.locationForCharacter(at: to - start).x
1082 context.fill(CGRect(x: point.x + x1, y: point.y + bounds.minY, width: max(0, x2 - x1), height: bounds.height))
1083 }
1084 context.restoreGState()
1085 }
1086
1087 private func drawEntities(at point: CGPoint) {
1088 guard let string = (textElement as? NSTextParagraph)?.attributedString else { return }
1089 string.enumerateAttribute(.orgEntityDisplay, in: NSRange(location: 0, length: string.length)) { value, range, _ in
1090 guard let display = value as? String,
1091 let line = textLineFragments.first(where: { NSLocationInRange(range.location, $0.characterRange) }) else { return }
1092 var attributes = string.attributes(at: range.location, effectiveRange: nil)
1093 attributes[.foregroundColor] = attributes[.orgEntityColor] ?? UIColor.label
1094 attributes[.orgEntityDisplay] = nil
1095 attributes[.orgEntityColor] = nil
1096 let x = line.locationForCharacter(at: range.location).x
1097 let bounds = line.typographicBounds
1098 NSAttributedString(string: display, attributes: attributes).draw(at: CGPoint(x: point.x + bounds.minX + x, y: point.y + bounds.minY))
1099 }
1100 }
1101}
1102#endif