Sources/OrgPresentation/Restyling.swift

49c5da97098ed000be935c19462d4102812b0471
orgstar/Sources/OrgPresentation/Restyling.swift

167 lines · 9400 bytes

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