Sources/OrgstarMobile/MobileEditor.swift

745599e8e905766da00da4d49c9b867ba4d6efb5
orgstar/Sources/OrgstarMobile/MobileEditor.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form