Sources/OrgPresentation/Restyling.swift

164 lines · 9261 bytes

12 symbols in this file
  1import Foundation
  2import OrgCore
  3
  4/// Styling done in passes from the start of the text: before `end` the text is styled, after
  5/// it the text waits for a pass. Always at a line start.
  6public struct StyledExtent: Sendable, Equatable {
  7    public private(set) var end = 0
  8
  9    public init() {}
 10
 11    public mutating func reset() { end = 0 }
 12
 13    /// The whole lines from `end`, about `size` units, now counted as styled; nil when all are.
 14    public mutating func next(_ size: Int, in text: NSString) -> Range<Int>? {
 15        guard end < text.length else { return nil }
 16        let target = min(text.length, end + size)
 17        let upper = target == text.length ? target : NSMaxRange(text.lineRange(for: NSRange(location: target, length: 0)))
 18        defer { end = upper }
 19        return end..<upper
 20    }
 21
 22    /// Keeps `end` on unstyled text: shifted past `edit`, or pulled back to the edited line when
 23    /// the edit reaches into unstyled text. `text` is the text after the edit.
 24    public mutating func map(through edit: TextEdit, in text: NSString) {
 25        if end >= edit.range.upperBound {
 26            end += edit.replacement.utf16.count - edit.range.count
 27        } else if end > edit.range.lowerBound {
 28            end = text.lineRange(for: NSRange(location: edit.range.lowerBound, length: 0)).location
 29        }
 30    }
 31}
 32
 33/// An attribute change styling makes, in the order `Presentation.styleChanges` gives.
 34public enum StyleChange: Sendable, Equatable {
 35    /// org-indent's paragraph style for a line.
 36    case indent(Presentation.LineIndent)
 37    /// A role over a range.
 38    case role(StyleRole, Range<Int>)
 39    /// Markup hidden off the revealed line.
 40    case hidden(Range<Int>)
 41}
 42
 43extension Presentation {
 44    /// The indents and roles for `range`, clipped to it, in ascending order of where they start,
 45    /// so each change lands at the end of the attribute runs made so far instead of moving the
 46    /// ones after it. Leading stars that `indented` and `hideStars` skip are left out; with
 47    /// `showMarkup` off, markup that `options` hides is hidden except on `revealed`. Also the
 48    /// ranges of runs that exclude sub- and superscripts, unclipped.
 49    public static func styleChanges(
 50        _ tree: OrgTree, in range: Range<Int>, highlighter: (any CodeHighlighter)?,
 51        indented: Bool, hideStars: Bool, showMarkup: Bool, options: EditingOptions, revealed: Range<Int>
 52    ) -> (changes: [StyleChange], scriptExclusions: [Range<Int>]) {
 53        var changes: [StyleChange] = []
 54        var scriptExclusions: [Range<Int>] = []
 55        var indents = (indented ? lineIndents(tree, in: range) : [])[...]
 56        func indent(before offset: Int) {
 57            while let line = indents.first, line.range.lowerBound <= offset {
 58                changes.append(.indent(line))
 59                indents.removeFirst()
 60            }
 61        }
 62        // Outer before inner still: an outer role never starts after an inner one, and the
 63        // index keeps the order of roles that start together. A src block's code runs come in
 64        // the highlighter's order, where later wins, so they sort as one.
 65        let runs = styles(tree, in: range, highlighter: highlighter)
 66        var starts: [Int] = []
 67        for (index, run) in runs.enumerated() {
 68            if case .syntax = run.role, index > 0, case .syntax = runs[index - 1].role {
 69                starts.append(starts[index - 1])
 70            } else {
 71                starts.append(run.range.lowerBound)
 72            }
 73        }
 74        for index in runs.indices.sorted(by: { (starts[$0], $0) < (starts[$1], $1) }) {
 75            let run = runs[index]
 76            indent(before: run.range.lowerBound)
 77            let clipped = run.range.clamped(to: range)
 78            guard !clipped.isEmpty else { continue }
 79            if skipsLeadingStars(run.role, indented: indented, hideStars: hideStars) { continue }
 80            if !showMarkup, hidesWithMarkup(run.role, options: options), !clipped.overlaps(revealed) {
 81                changes.append(.hidden(clipped))
 82            } else {
 83                changes.append(.role(run.role, clipped))
 84            }
 85            if excludesScripts(run.role) { scriptExclusions.append(run.range) }
 86        }
 87        indent(before: range.upperBound)
 88        return (changes, scriptExclusions)
 89    }
 90
 91    /// The region an edit affects in one version of the tree: inside the innermost section
 92    /// holding the edited lines (plus the line after), every element that overlaps them or the
 93    /// line on either side. A changed heading line, or an added or removed heading, widens it
 94    /// to that section's whole own body; outside a section with a heading, the elements around
 95    /// the edit already cover what changes. Run on the old and the new tree, the union covers
 96    /// elements that grew and elements that shrank.
 97    public static func affectedRange(_ tree: OrgTree, _ text: NSString, _ start: Int, _ end: Int, touchedHeadings: Bool) -> Range<Int> {
 98        let lines = text.lineRange(for: NSRange(location: start, length: min(end + 1, text.length) - start))
 99        let lineRange = lines.location..<(lines.location + lines.length)
100        let around = max(0, lineRange.lowerBound - 1)..<min(text.length, lineRange.upperBound + 1)
101        var container = tree.root
102        while let child = container.child(containing: lineRange.lowerBound),
103              child.kind == .section || child.kind == .zerothSection,
104              lineRange.upperBound <= child.range.upperBound {
105            container = child
106        }
107        var lower = lineRange.lowerBound
108        var upper = lineRange.upperBound
109        // Tables and lists carry no styling of their own, so inside them only the rows or
110        // items around the edit change, however large they are.
111        func overlapping(_ nodes: [SyntaxNode]) -> [SyntaxNode] {
112            nodes.filter { $0.range.overlaps(around) }.flatMap { node -> [SyntaxNode] in
113                guard [.table, .plainList, .item].contains(node.kind) else { return [node] }
114                let inner = overlapping(node.children(overlapping: around))
115                return inner.isEmpty ? [node] : inner
116            }
117        }
118        for child in overlapping(container.children(overlapping: around)) {
119            lower = min(lower, child.range.lowerBound)
120            upper = max(upper, child.range.upperBound)
121        }
122        if let heading = container.firstChild(.heading), touchedHeadings || heading.range.overlaps(lineRange) {
123            lower = min(lower, container.range.lowerBound)
124            upper = max(upper, container.firstChild(.section)?.range.lowerBound ?? container.range.upperBound)
125        }
126        return lower..<min(upper, text.length)
127    }
128
129    /// Whether a heading line touches `start..<end` or starts right after it, where joining
130    /// lines could take it away.
131    public static func headingLineNear(_ start: Int, _ end: Int, in text: NSString) -> Bool {
132        let length = min(end + 1, text.length) - start
133        guard length >= 0 else { return false }
134        let lines = text.substring(with: text.lineRange(for: NSRange(location: start, length: length)))
135        return lines.split(separator: "\n", omittingEmptySubsequences: false).contains { line in
136            let stars = line.prefix { $0 == "*" }
137            let after = line.dropFirst(stars.count)
138            return !stars.isEmpty && (after.isEmpty || after.first == " " || after.first == "\t" || after.first == "\r")
139        }
140    }
141
142    /// What `edit` makes style again: the region it affects in the old tree, mapped through it,
143    /// and in the new one. Not clamped to the new text.
144    public static func restyleRange(for edit: TextEdit, old: (tree: OrgTree, text: NSString), new: (tree: OrgTree, text: NSString)) -> Range<Int> {
145        let newEnd = edit.range.lowerBound + edit.replacement.utf16.count
146        let touchedHeadings = headingLineNear(edit.range.lowerBound, edit.range.upperBound, in: old.text)
147            || headingLineNear(edit.range.lowerBound, newEnd, in: new.text)
148        let oldAffected = affectedRange(old.tree, old.text, edit.range.lowerBound, edit.range.upperBound, touchedHeadings: touchedHeadings)
149        let newAffected = affectedRange(new.tree, new.text, edit.range.lowerBound, newEnd, touchedHeadings: touchedHeadings)
150        let delta = edit.replacement.utf16.count - edit.range.count
151        let oldMapped = oldAffected.lowerBound..<(oldAffected.upperBound >= edit.range.upperBound ? oldAffected.upperBound + delta : newEnd)
152        return min(oldMapped.lowerBound, newAffected.lowerBound)..<max(oldMapped.upperBound, newAffected.upperBound)
153    }
154
155    /// Whether the lines around `range`, and the line after it (a deleted newline joins it to
156    /// them), hold a block delimiter or a fixed-width line.
157    public static func mayChangeBlocks(_ text: NSString, _ range: Range<Int>) -> Bool {
158        let start = min(range.lowerBound, text.length)
159        let end = min(range.upperBound + 1, text.length)
160        let lines = text.lineRange(for: NSRange(location: start, length: end - start))
161        let content = text.substring(with: lines)
162        return content.contains("#+") || content.range(of: "(^|\\n)([ \\t]*:|\\*)", options: .regularExpression) != nil
163    }
164}