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