Sources/OrgstarMobile/MobileEditor.swift

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