Tests/OrgPresentationTests/RestylingTests.swift

design-themes-widgets
orgstar/Tests/OrgPresentationTests/RestylingTests.swift history · blame · raw

245 lines · 12065 bytes

  1import Foundation
  2import OrgCore
  3import Testing
  4@testable import OrgPresentation
  5
  6struct StyledExtentTests {
  7    @Test func chunksEndAtLineStartsAndCoverTheText() {
  8        let text = String(repeating: "a line of text\n", count: 100) + "last" as NSString
  9        var extent = StyledExtent()
 10        var chunks: [Range<Int>] = []
 11        while let chunk = extent.next(100, in: text) { chunks.append(chunk) }
 12        #expect(chunks.first?.lowerBound == 0)
 13        #expect(chunks.last?.upperBound == text.length)
 14        #expect(extent.end == text.length)
 15        for (a, b) in zip(chunks, chunks.dropFirst()) { #expect(a.upperBound == b.lowerBound) }
 16        for chunk in chunks.dropLast() {
 17            #expect(chunk.count >= 100)
 18            #expect(text.character(at: chunk.upperBound - 1) == 0x0A)
 19        }
 20        extent.reset()
 21        #expect(extent.end == 0)
 22    }
 23
 24    @Test func editsMoveOrPullBackTheEnd() {
 25        let text = String(repeating: "line\n", count: 10) as NSString
 26        var extent = StyledExtent()
 27        _ = extent.next(12, in: text)
 28        #expect(extent.end == 15)
 29        // Before: shifted.
 30        var before = extent
 31        before.map(through: TextEdit(range: 0..<0, replacement: "abc"), in: "abc" + (text as String) as NSString)
 32        #expect(before.end == 18)
 33        // Across: pulled back to the edited line.
 34        var across = extent
 35        let edited = text.replacingCharacters(in: NSRange(location: 12, length: 5), with: "") as NSString
 36        across.map(through: TextEdit(range: 12..<17, replacement: ""), in: edited)
 37        #expect(across.end == 10)
 38        // After: unchanged.
 39        var after = extent
 40        after.map(through: TextEdit(range: 20..<20, replacement: "x"), in: text)
 41        #expect(after.end == 15)
 42    }
 43}
 44
 45struct StyleChangeTests {
 46    /// Highlights whose later runs overlap earlier ones that start before them.
 47    struct Overlapping: CodeHighlighter {
 48        func highlights(language: String, code: String) -> [(range: Range<Int>, category: SyntaxCategory)] {
 49            [(5..<7, .string), (0..<7, .keyword), (2..<4, .comment)]
 50        }
 51    }
 52
 53    static let sample = """
 54        #+TITLE: Sample
 55        * TODO [#A] Heading with *bold* and [[https://a.b][a link]] :tag:
 56        SCHEDULED: <2026-11-21 Sat>
 57        :PROPERTIES:
 58        :ID: x
 59        :END:
 60        Text with /italic/, =code=, ~verb~ and x^{2} and \\alpha.
 61        - item *one* [ ]
 62          - nested [[file:a.org]]
 63        | a | *b* |
 64        |---+-----|
 65        #+begin_src sh
 66        echo hi
 67        #+end_src
 68        ** DONE Second
 69        #+begin_quote
 70        quoted *text*
 71        #+end_quote
 72
 73        """
 74
 75    /// Every role on one attribute, so the last one set over a character shows.
 76    private func applied(_ changes: [StyleChange], length: Int) -> NSAttributedString {
 77        let out = NSMutableAttributedString(string: String(repeating: " ", count: length))
 78        let role = NSAttributedString.Key("role")
 79        let indent = NSAttributedString.Key("indent")
 80        for change in changes {
 81            switch change {
 82            case .indent(let line): out.addAttribute(indent, value: "\(line.firstLine) \(line.wrapped)", range: NSRange(line.range))
 83            case .role(let r, let range): out.addAttribute(role, value: "\(r)", range: NSRange(range))
 84            case .hidden(let range): out.addAttribute(role, value: "hidden", range: NSRange(range))
 85            }
 86        }
 87        return out
 88    }
 89
 90    /// Indents first, then roles in `Presentation.styles` order.
 91    private func inStylesOrder(_ tree: OrgTree, _ range: Range<Int>, showMarkup: Bool, revealed: Range<Int>) -> [StyleChange] {
 92        var changes = Presentation.lineIndents(tree, in: range).map(StyleChange.indent)
 93        for run in Presentation.styles(tree, in: range, highlighter: Overlapping()) {
 94            let clipped = run.range.clamped(to: range)
 95            guard !clipped.isEmpty else { continue }
 96            if !showMarkup, Presentation.hidesWithMarkup(run.role, options: .org), !clipped.overlaps(revealed) {
 97                changes.append(.hidden(clipped))
 98            } else {
 99                changes.append(.role(run.role, clipped))
100            }
101        }
102        return changes
103    }
104
105    @Test(arguments: [true, false]) func ascendingOrderSetsWhatStylesOrderSets(showMarkup: Bool) {
106        let tree = OrgParser.parse(Self.sample)
107        let length = Self.sample.utf16.count
108        let revealed = 16..<80
109        for range in [0..<length, 16..<200, 300..<length] {
110            let (changes, _) = Presentation.styleChanges(
111                tree, in: range, highlighter: Overlapping(), indented: true, hideStars: false,
112                showMarkup: showMarkup, options: .org, revealed: revealed
113            )
114            let expected = inStylesOrder(tree, range, showMarkup: showMarkup, revealed: revealed)
115            #expect(changes.count == expected.count)
116            #expect(applied(changes, length: length).isEqual(to: applied(expected, length: length)))
117        }
118    }
119
120    @Test func changesStartInAscendingOrder() {
121        let tree = OrgParser.parse(Self.sample)
122        let (changes, exclusions) = Presentation.styleChanges(
123            tree, in: 0..<Self.sample.utf16.count, highlighter: nil, indented: true, hideStars: false,
124            showMarkup: true, options: .org, revealed: 0..<0
125        )
126        let starts = changes.map { change in
127            switch change {
128            case .indent(let line): line.range.lowerBound
129            case .role(_, let range), .hidden(let range): range.lowerBound
130            }
131        }
132        #expect(starts == starts.sorted())
133        #expect(!exclusions.isEmpty)
134    }
135
136    @Test func leadingStarsAndHiddenMarkup() {
137        let text = "** a *b*\n"
138        let tree = OrgParser.parse(text)
139        func changes(indented: Bool, showMarkup: Bool, revealed: Range<Int>) -> [StyleChange] {
140            var options = EditingOptions.org
141            options.hideEmphasisMarkers = true
142            return Presentation.styleChanges(
143                tree, in: 0..<text.utf16.count, highlighter: nil, indented: indented, hideStars: false,
144                showMarkup: showMarkup, options: options, revealed: revealed
145            ).changes
146        }
147        #expect(changes(indented: true, showMarkup: true, revealed: 0..<0).contains(.role(.leadingStars, 0..<1)))
148        #expect(!changes(indented: false, showMarkup: true, revealed: 0..<0).contains(.role(.leadingStars, 0..<1)))
149        #expect(changes(indented: false, showMarkup: false, revealed: 0..<0).contains(.hidden(5..<6)))
150        #expect(changes(indented: false, showMarkup: false, revealed: 0..<9).contains(.role(.markup, 5..<6)))
151        #expect(changes(indented: false, showMarkup: true, revealed: 0..<0).filter { if case .indent = $0 { true } else { false } }.isEmpty)
152    }
153}
154
155struct RestyleRangeTests {
156    private func range(_ old: String, _ edit: TextEdit) -> Range<Int> {
157        var new = Array(old.utf16)
158        new.replaceSubrange(edit.range, with: Array(edit.replacement.utf16))
159        let newText = String(decoding: new, as: UTF16.self)
160        return Presentation.restyleRange(
161            for: edit, old: (OrgParser.parse(old), old as NSString), new: (OrgParser.parse(newText), newText as NSString)
162        )
163    }
164
165    @Test func aParagraphEditStaysInItsParagraph() {
166        let text = String(repeating: "* Heading\nSome text here.\n\nMore text.\n\n", count: 2_000)
167        let at = (text as NSString).range(of: "Some text", options: [], range: NSRange(location: 40_000, length: 1_000)).location
168        let affected = range(text, TextEdit(range: at..<at, replacement: "x"))
169        #expect(affected.contains(at))
170        #expect(affected.count < 100)
171    }
172
173    @Test func aHeadingEditWidensToItsSection() {
174        let text = "* A\nbody\n\nmore body\n* B\nnext\n"
175        let affected = range(text, TextEdit(range: 2..<3, replacement: "AB"))
176        #expect(affected.lowerBound == 0)
177        #expect(affected.upperBound >= ("* AB\nbody\n\nmore body\n" as NSString).length)
178    }
179
180    /// A replacement across the newline before a top-level heading, as a keyboard makes: the
181    /// sections on either side change, not the text from the start of the file.
182    @Test func aReplacementBeforeATopLevelHeadingStaysNearIt() {
183        let text = String(repeating: "* TODO Project :work:\n** Section\nSome *text*.\n\n- item one\n- item two [ ]\n\n", count: 2_000)
184        let at = (text as NSString).range(of: "\n\n* TODO", options: [], range: NSRange(location: 40_000, length: 1_000)).location + 1
185        let affected = range(text, TextEdit(range: at..<(at + 1), replacement: "x\n"))
186        #expect(affected.contains(at))
187        #expect(affected.count < 200)
188    }
189
190    /// Restyling only what an edit affects leaves the same styling as restyling everything.
191    @Test(arguments: ["a", "\n", "* ", "#+end_src\n", ""])
192    func restylingTheRangeMatchesRestylingAll(replacement: String) {
193        let text = StyleChangeTests.sample + "* B\n:PROPERTIES:\n:ID: x\n:END:\n| a |\n|---|\n\n- a\n  - b\n* C\nend\n"
194        let length = text.utf16.count
195        let oldTree = OrgParser.parse(text)
196        let old = styled(oldTree, in: 0..<length)
197        for at in 0..<length {
198            let edit = TextEdit(range: at..<(replacement.isEmpty ? at + 1 : at), replacement: replacement)
199            let newText = (text as NSString).replacingCharacters(in: NSRange(edit.range), with: replacement)
200            let newTree = OrgParser.parse(newText)
201            let affected = Presentation.restyleRange(for: edit, old: (oldTree, text as NSString), new: (newTree, newText as NSString))
202            let restyle = affected.clamped(to: 0..<newText.utf16.count)
203            let incremental = NSMutableAttributedString(attributedString: old)
204            incremental.replaceCharacters(in: NSRange(edit.range), with: replacement)
205            incremental.setAttributes([:], range: NSRange(restyle))
206            apply(styled(newTree, in: restyle), to: incremental, at: restyle.lowerBound)
207            let whole = styled(newTree, in: 0..<newText.utf16.count)
208            #expect(incremental.isEqual(to: whole), "edit at \(at)")
209        }
210    }
211
212    /// Roles and indents for `range` of `tree`, on a string of spaces as long as the range.
213    private func styled(_ tree: OrgTree, in range: Range<Int>) -> NSAttributedString {
214        let (changes, _) = Presentation.styleChanges(
215            tree, in: range, highlighter: nil, indented: true, hideStars: false, showMarkup: true, options: .org, revealed: 0..<0
216        )
217        let out = NSMutableAttributedString(string: (tree.text as NSString).substring(with: NSRange(range)))
218        for change in changes {
219            switch change {
220            case .indent(let line): out.addAttribute(.init("indent"), value: "\(line.firstLine) \(line.wrapped)", range: NSRange(line.range.shifted(-range.lowerBound)))
221            case .role(let role, let r): out.addAttribute(.init("role"), value: "\(role)", range: NSRange(r.shifted(-range.lowerBound)))
222            case .hidden(let r): out.addAttribute(.init("role"), value: "hidden", range: NSRange(r.shifted(-range.lowerBound)))
223            }
224        }
225        return out
226    }
227
228    private func apply(_ part: NSAttributedString, to string: NSMutableAttributedString, at offset: Int) {
229        part.enumerateAttributes(in: NSRange(location: 0, length: part.length)) { attributes, range, _ in
230            string.addAttributes(attributes, range: NSRange(location: offset + range.location, length: range.length))
231        }
232    }
233
234    @Test func closingABlockCoversTheBlock() {
235        let text = "Intro.\n#+begin_src sh\necho\nmore\n\nend\n"
236        let at = (text as NSString).length
237        let affected = range(text, TextEdit(range: at..<at, replacement: "#+end_src\n"))
238        #expect(affected.lowerBound <= ("Intro.\n" as NSString).length)
239        #expect(affected.upperBound >= at + 10)
240    }
241}
242
243private extension Range<Int> {
244    func shifted(_ by: Int) -> Range<Int> { (lowerBound + by)..<(upperBound + by) }
245}