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