Commit 2f17964617
Verified · cmc
Layout: unified · split
Sources/OrgEditorAppKit/OrgEditor+Styling.swift +9 −71
| @@ -26,42 +26,18 @@ extension OrgEditor { | ||
| 26 | 26 | } |
| 27 | 27 | return |
| 28 | 28 | } |
| 29 | // Indents and roles go on together in ascending order, so each change lands at the end | |
| 30 | // of the runs made so far instead of moving the ones after it. | |
| 31 | var indents = (indented ? Presentation.lineIndents(document.tree, in: range) : [])[...] | |
| 32 | func indent(before offset: Int) { | |
| 33 | while let line = indents.first, line.range.lowerBound <= offset { | |
| 34 | storage.addAttribute(.paragraphStyle, value: paragraphStyle(line.firstLine, line.wrapped), range: NSRange(line.range)) | |
| 35 | indents.removeFirst() | |
| 36 | } | |
| 37 | } | |
| 38 | 29 | let revealed = caretLine |
| 39 | var scriptExclusions: [Range<Int>] = [] | |
| 40 | // Outer before inner still: an outer role never starts after an inner one, and the | |
| 41 | // index keeps the order of roles that start together. A src block's code runs come in | |
| 42 | // the highlighter's order, where later wins, so they sort as one. | |
| 43 | let styles = Presentation.styles(document.tree, in: range, highlighter: highlighter) | |
| 44 | var starts: [Int] = [] | |
| 45 | for (index, run) in styles.enumerated() { | |
| 46 | if case .syntax = run.role, index > 0, case .syntax = styles[index - 1].role { | |
| 47 | starts.append(starts[index - 1]) | |
| 48 | } else { | |
| 49 | starts.append(run.range.lowerBound) | |
| 50 | } | |
| 51 | } | |
| 52 | for index in styles.indices.sorted(by: { (starts[$0], $0) < (starts[$1], $1) }) { | |
| 53 | let run = styles[index] | |
| 54 | indent(before: run.range.lowerBound) | |
| 55 | guard let clipped = clip(run.range, to: range) else { continue } | |
| 56 | if Presentation.skipsLeadingStars(run.role, indented: indented, hideStars: hideStars) { continue } | |
| 57 | if !showMarkup, Presentation.hidesWithMarkup(run.role, options: options), NSIntersectionRange(clipped, revealed).length == 0 { | |
| 58 | storage.addAttributes(theme.hidden, range: clipped) | |
| 59 | } else { | |
| 60 | theme.apply(run.role, to: storage, range: clipped) | |
| 30 | let (changes, scriptExclusions) = Presentation.styleChanges( | |
| 31 | document.tree, in: range, highlighter: highlighter, indented: indented, hideStars: hideStars, | |
| 32 | showMarkup: showMarkup, options: options, revealed: revealed.location..<NSMaxRange(revealed) | |
| 33 | ) | |
| 34 | for change in changes { | |
| 35 | switch change { | |
| 36 | case .indent(let line): storage.addAttribute(.paragraphStyle, value: paragraphStyle(line.firstLine, line.wrapped), range: NSRange(line.range)) | |
| 37 | case .role(let role, let range): theme.apply(role, to: storage, range: NSRange(range)) | |
| 38 | case .hidden(let range): storage.addAttributes(theme.hidden, range: NSRange(range)) | |
| 61 | 39 | } |
| 62 | if Presentation.excludesScripts(run.role) { scriptExclusions.append(run.range) } | |
| 63 | 40 | } |
| 64 | indent(before: range.upperBound) | |
| 65 | 41 | if theme.mixedPitch { |
| 66 | 42 | for prefix in Presentation.fixedPitchPrefixes(storage.string as NSString, in: range) { |
| 67 | 43 | guard let clipped = clip(prefix, to: range) else { continue } |
| @@ -138,43 +114,5 @@ extension OrgEditor { | ||
| 138 | 114 | let clipped = run.clamped(to: range) |
| 139 | 115 | return clipped.isEmpty ? nil : NSRange(clipped) |
| 140 | 116 | } |
| 141 | ||
| 142 | /// The region an edit affects in one version of the tree: inside the innermost section | |
| 143 | /// holding the edited lines (plus the line after), every element that overlaps them or the | |
| 144 | /// line on either side. A changed heading line, or an added or removed heading, widens it | |
| 145 | /// to that section's whole own body. Run on the old and the new tree, the union covers | |
| 146 | /// elements that grew and elements that shrank. | |
| 147 | static func affectedRange(_ tree: OrgTree, _ text: NSString, _ start: Int, _ end: Int, touchedHeadings: Bool) -> Range<Int> { | |
| 148 | let lines = text.lineRange(for: NSRange(location: start, length: min(end + 1, text.length) - start)) | |
| 149 | let lineRange = lines.location..<(lines.location + lines.length) | |
| 150 | let around = max(0, lineRange.lowerBound - 1)..<min(text.length, lineRange.upperBound + 1) | |
| 151 | var container = tree.root | |
| 152 | while let child = container.child(containing: lineRange.lowerBound), | |
| 153 | child.kind == .section || child.kind == .zerothSection, | |
| 154 | lineRange.upperBound <= child.range.upperBound { | |
| 155 | container = child | |
| 156 | } | |
| 157 | var lower = lineRange.lowerBound | |
| 158 | var upper = lineRange.upperBound | |
| 159 | // Tables and lists carry no styling of their own, so inside them only the rows or | |
| 160 | // items around the edit change, however large they are. | |
| 161 | func overlapping(_ nodes: [SyntaxNode]) -> [SyntaxNode] { | |
| 162 | nodes.filter { $0.range.overlaps(around) }.flatMap { node -> [SyntaxNode] in | |
| 163 | guard [.table, .plainList, .item].contains(node.kind) else { return [node] } | |
| 164 | let inner = overlapping(node.children(overlapping: around)) | |
| 165 | return inner.isEmpty ? [node] : inner | |
| 166 | } | |
| 167 | } | |
| 168 | for child in overlapping(container.children(overlapping: around)) { | |
| 169 | lower = min(lower, child.range.lowerBound) | |
| 170 | upper = max(upper, child.range.upperBound) | |
| 171 | } | |
| 172 | let heading = container.firstChild(.heading) | |
| 173 | if touchedHeadings || heading.map({ $0.range.overlaps(lineRange) }) == true { | |
| 174 | lower = min(lower, container.range.lowerBound) | |
| 175 | upper = max(upper, container.firstChild(.section)?.range.lowerBound ?? container.range.upperBound) | |
| 176 | } | |
| 177 | return lower..<min(upper, text.length) | |
| 178 | } | |
| 179 | 117 | } |
| 180 | 118 | #endif |
Sources/OrgEditorAppKit/OrgEditor.swift +13 −37
| @@ -51,9 +51,10 @@ public final class OrgEditor: NSObject { | ||
| 51 | 51 | var previousSelection = 0 |
| 52 | 52 | /// The selection shaded block lines last drew. |
| 53 | 53 | private var previousSelectionRange = NSRange(location: 0, length: 0) |
| 54 | /// Text before this offset is styled; after it, only base attributes until the background | |
| 55 | /// passes reach it. Always at a line start. | |
| 56 | private(set) var styledUpTo = 0 | |
| 54 | /// Text before its end is styled; after it, only base attributes until the background | |
| 55 | /// passes reach it. | |
| 56 | private var styled = StyledExtent() | |
| 57 | var styledUpTo: Int { styled.end } | |
| 57 | 58 | private var stylingScheduled = false |
| 58 | 59 | /// One paragraph style object per indent pair, shared by every line that uses it. |
| 59 | 60 | var paragraphStyles: [IndentKey: NSParagraphStyle] = [:] |
| @@ -265,7 +266,7 @@ public final class OrgEditor: NSObject { | ||
| 265 | 266 | view.lineIndex = lines |
| 266 | 267 | view.updateGutter() |
| 267 | 268 | } |
| 268 | styledUpTo = 0 | |
| 269 | styled.reset() | |
| 269 | 270 | revealedLine = caretLine |
| 270 | 271 | styleNextChunk(Self.firstStyleChunk) |
| 271 | 272 | scheduleStyling() |
| @@ -275,12 +276,8 @@ public final class OrgEditor: NSObject { | ||
| 275 | 276 | |
| 276 | 277 | /// Styles whole lines from the watermark onward, about `size` units. |
| 277 | 278 | func styleNextChunk(_ size: Int) { |
| 278 | let text = textView.textStorage!.string as NSString | |
| 279 | guard styledUpTo < text.length else { return } | |
| 280 | let target = min(text.length, styledUpTo + size) | |
| 281 | let end = target == text.length ? target : NSMaxRange(text.lineRange(for: NSRange(location: target, length: 0))) | |
| 282 | restyleOutsideEditing(styledUpTo..<end) | |
| 283 | styledUpTo = end | |
| 279 | guard let range = styled.next(size, in: textView.textStorage!.string as NSString) else { return } | |
| 280 | restyleOutsideEditing(range) | |
| 284 | 281 | } |
| 285 | 282 | |
| 286 | 283 | /// Every text view's own colors and font, and the line numbers'. |
| @@ -304,7 +301,7 @@ public final class OrgEditor: NSObject { | ||
| 304 | 301 | |
| 305 | 302 | /// Styles the whole file again, a screenful now and the rest in the background. |
| 306 | 303 | private func restyleEverything() { |
| 307 | styledUpTo = 0 | |
| 304 | styled.reset() | |
| 308 | 305 | revealedLine = caretLine |
| 309 | 306 | styleNextChunk(Self.firstStyleChunk) |
| 310 | 307 | scheduleStyling() |
| @@ -781,9 +778,7 @@ public final class OrgEditor: NSObject { | ||
| 781 | 778 | let oldText = document.text as NSString |
| 782 | 779 | let newText = storage.string as NSString |
| 783 | 780 | let newEnd = edit.range.lowerBound + replacement.utf16.count |
| 784 | let touchedHeadings = Self.headingLineNear(edit.range.lowerBound, edit.range.upperBound, in: oldText) | |
| 785 | || Self.headingLineNear(edit.range.lowerBound, newEnd, in: newText) | |
| 786 | let oldAffected = Self.affectedRange(document.tree, oldText, edit.range.lowerBound, edit.range.upperBound, touchedHeadings: touchedHeadings) | |
| 781 | let oldTree = document.tree | |
| 787 | 782 | do { |
| 788 | 783 | try document.apply([edit], baseRevision: document.revision) |
| 789 | 784 | } catch { |
| @@ -792,17 +787,11 @@ public final class OrgEditor: NSObject { | ||
| 792 | 787 | } |
| 793 | 788 | // Keep the watermark on unstyled text: shift it past the edit, or pull it back to the |
| 794 | 789 | // edited line when the edit reaches into unstyled text. |
| 795 | if styledUpTo >= edit.range.upperBound { | |
| 796 | styledUpTo += edit.replacement.utf16.count - edit.range.count | |
| 797 | } else if styledUpTo > edit.range.lowerBound { | |
| 798 | styledUpTo = (storage.string as NSString).lineRange(for: NSRange(location: edit.range.lowerBound, length: 0)).location | |
| 799 | } | |
| 790 | styled.map(through: edit, in: newText) | |
| 800 | 791 | let oldHidden = hidden.all |
| 801 | let newAffected = Self.affectedRange(document.tree, newText, edit.range.lowerBound, newEnd, touchedHeadings: touchedHeadings) | |
| 802 | let delta = edit.replacement.utf16.count - edit.range.count | |
| 803 | let oldMapped = oldAffected.lowerBound..<(oldAffected.upperBound >= edit.range.upperBound ? oldAffected.upperBound + delta : newEnd) | |
| 792 | let affected = Presentation.restyleRange(for: edit, old: (oldTree, oldText), new: (document.tree, newText)) | |
| 804 | 793 | view = view.mapped(through: [edit]).pruned(to: document.tree, wrappers: false) |
| 805 | mapWrapperFolds(through: edit, near: min(oldMapped.lowerBound, newAffected.lowerBound)..<max(oldMapped.upperBound, newAffected.upperBound)) | |
| 794 | mapWrapperFolds(through: edit, near: affected) | |
| 806 | 795 | if let narrowed { self.narrowed = ViewState(selection: [narrowed]).mapped(through: [edit]).selection[0] } |
| 807 | 796 | mapVimPositions(through: edit) |
| 808 | 797 | vim.changed(edit) |
| @@ -810,7 +799,7 @@ public final class OrgEditor: NSObject { | ||
| 810 | 799 | let oldHighlights = ViewState(selection: highlights).mapped(through: [edit]).selection |
| 811 | 800 | highlights = [] |
| 812 | 801 | updateHidden() |
| 813 | restyle(min(oldMapped.lowerBound, newAffected.lowerBound)..<min(max(oldMapped.upperBound, newAffected.upperBound), newText.length), in: storage) | |
| 802 | restyle(affected.lowerBound..<min(affected.upperBound, newText.length), in: storage) | |
| 814 | 803 | for table in shrunk.map(through: edit, in: storage.string, command: commandEditing) { restyle(table.lowerBound..<min(table.upperBound, newText.length), in: storage) } |
| 815 | 804 | for range in oldHighlights where range.upperBound <= newText.length { |
| 816 | 805 | let lines = newText.lineRange(for: NSRange(range)) |
| @@ -839,19 +828,6 @@ public final class OrgEditor: NSObject { | ||
| 839 | 828 | onChange?() |
| 840 | 829 | } |
| 841 | 830 | |
| 842 | /// Whether a heading line touches `start..<end` or starts right after it, where joining | |
| 843 | /// lines could take it away. | |
| 844 | static func headingLineNear(_ start: Int, _ end: Int, in text: NSString) -> Bool { | |
| 845 | let length = min(end + 1, text.length) - start | |
| 846 | guard length >= 0 else { return false } | |
| 847 | let lines = text.substring(with: text.lineRange(for: NSRange(location: start, length: length))) | |
| 848 | return lines.split(separator: "\n", omittingEmptySubsequences: false).contains { line in | |
| 849 | let stars = line.prefix { $0 == "*" } | |
| 850 | let after = line.dropFirst(stars.count) | |
| 851 | return !stars.isEmpty && (after.isEmpty || after.first == " " || after.first == "\t" || after.first == "\r") | |
| 852 | } | |
| 853 | } | |
| 854 | ||
| 855 | 831 | private func mapRange(_ range: Range<Int>, through edit: TextEdit) -> Range<Int> { |
| 856 | 832 | let mapped = ViewState(selection: [range]).mapped(through: [edit]).selection[0] |
| 857 | 833 | return mapped |
Sources/OrgPresentation/Restyling.swift added +154
| @@ -0,0 +1,154 @@ | ||
| 1 | import Foundation | |
| 2 | import 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. | |
| 6 | public 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. | |
| 34 | public 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 | ||
| 43 | extension 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 | } | |
Sources/OrgstarMobile/MobileEditor+Styling.swift +48 −24
| @@ -14,10 +14,40 @@ extension MobileEditor { | ||
| 14 | 14 | textView.textStorage.setAttributedString(NSAttributedString(string: text, attributes: theme.base)) |
| 15 | 15 | loading = false |
| 16 | 16 | shaded.set(Presentation.shadedBlocks(document.tree), folded: []) |
| 17 | restyle(0..<(text as NSString).length) | |
| 17 | restartStyling() | |
| 18 | 18 | textView.typingAttributes = theme.base |
| 19 | 19 | } |
| 20 | 20 | |
| 21 | /// Styled before the first render: more than a screenful. | |
| 22 | static let firstStyleChunk = 30_000 | |
| 23 | /// Styled per run-loop turn afterwards, short enough to keep scrolling and typing smooth. | |
| 24 | static let styleChunk = 50_000 | |
| 25 | ||
| 26 | /// Styles the whole file again, a screenful now and the rest in the background. | |
| 27 | func restartStyling() { | |
| 28 | styled.reset() | |
| 29 | revealedLine = caretLine | |
| 30 | styleNextChunk(Self.firstStyleChunk) | |
| 31 | scheduleStyling() | |
| 32 | } | |
| 33 | ||
| 34 | /// Styles whole lines from the end of the styled text onward, about `size` units. | |
| 35 | private func styleNextChunk(_ size: Int) { | |
| 36 | guard let range = styled.next(size, in: textView.textStorage.string as NSString) else { return } | |
| 37 | restyle(range) | |
| 38 | } | |
| 39 | ||
| 40 | private func scheduleStyling() { | |
| 41 | guard !stylingScheduled, styled.end < textView.textStorage.length else { return } | |
| 42 | stylingScheduled = true | |
| 43 | DispatchQueue.main.async { [weak self] in | |
| 44 | guard let self else { return } | |
| 45 | self.stylingScheduled = false | |
| 46 | self.styleNextChunk(Self.styleChunk) | |
| 47 | self.scheduleStyling() | |
| 48 | } | |
| 49 | } | |
| 50 | ||
| 21 | 51 | /// The text view's own colors, and the block band's. |
| 22 | 52 | func applyThemeToView() { |
| 23 | 53 | for view in textViews { applyThemeToView(view) } |
| @@ -87,7 +117,7 @@ extension MobileEditor { | ||
| 87 | 117 | return |
| 88 | 118 | } |
| 89 | 119 | keepingTopLine { |
| 90 | if showsImages { restyle(0..<textView.textStorage.length) } | |
| 120 | if showsImages { restartStyling() } | |
| 91 | 121 | for manager in layoutManagers { |
| 92 | 122 | manager.invalidateRenderingAttributes(for: manager.documentRange) |
| 93 | 123 | manager.invalidateLayout(for: manager.documentRange) |
| @@ -95,12 +125,12 @@ extension MobileEditor { | ||
| 95 | 125 | } |
| 96 | 126 | } |
| 97 | 127 | |
| 98 | /// Styles the whole file again. | |
| 128 | /// Styles the whole file again, a screenful now and the rest in the background. | |
| 99 | 129 | func restyleAll() { |
| 100 | 130 | let interval = Perf.begin("editor.restyleAll") |
| 101 | 131 | defer { interval.end() } |
| 102 | 132 | keepingTopLine { |
| 103 | restyle(0..<textView.textStorage.length) | |
| 133 | restartStyling() | |
| 104 | 134 | for manager in layoutManagers { manager.invalidateLayout(for: manager.documentRange) } |
| 105 | 135 | } |
| 106 | 136 | } |
| @@ -139,6 +169,8 @@ extension MobileEditor { | ||
| 139 | 169 | change() |
| 140 | 170 | guard let anchor, anchor.offset > 0, let location = content.location(start, offsetBy: anchor.offset), |
| 141 | 171 | let above = NSTextRange(location: start, end: location) else { return } |
| 172 | // Styled now, not in the background passes, which would lay the text out again. | |
| 173 | while styled.end < anchor.offset { styleNextChunk(Self.styleChunk) } | |
| 142 | 174 | manager.ensureLayout(for: above) |
| 143 | 175 | guard let fragment = manager.textLayoutFragment(for: location) else { return } |
| 144 | 176 | let frame = fragment.layoutFragmentFrame |
| @@ -161,15 +193,13 @@ extension MobileEditor { | ||
| 161 | 193 | guard let self, let range = self.restyleScheduled else { return } |
| 162 | 194 | self.restyleScheduled = nil |
| 163 | 195 | self.shaded.set(Presentation.shadedBlocks(self.document.tree), folded: []) |
| 164 | // Small files are restyled whole: a heading or block line changes what follows it. | |
| 165 | let length = self.textView.textStorage.length | |
| 166 | self.restyle(length < 60_000 ? 0..<length : range) | |
| 196 | self.restyle(range) | |
| 167 | 197 | self.updateHidden() |
| 168 | 198 | self.textView.typingAttributes = self.theme.base |
| 169 | 199 | } |
| 170 | 200 | } |
| 171 | 201 | |
| 172 | private var caretLine: NSRange { | |
| 202 | var caretLine: NSRange { | |
| 173 | 203 | let text = textView.textStorage.string as NSString |
| 174 | 204 | return text.lineRange(for: NSRange(location: min(textView.selectedRange.location, text.length), length: 0)) |
| 175 | 205 | } |
| @@ -186,23 +216,17 @@ extension MobileEditor { | ||
| 186 | 216 | let whole = lines.location..<NSMaxRange(lines) |
| 187 | 217 | storage.beginEditing() |
| 188 | 218 | storage.setAttributes(theme.base, range: lines) |
| 189 | if indented { | |
| 190 | for line in Presentation.lineIndents(document.tree, in: whole) { | |
| 191 | storage.addAttribute(.paragraphStyle, value: paragraphStyle(line.firstLine, line.wrapped), range: NSRange(line.range)) | |
| 192 | } | |
| 193 | } | |
| 194 | 219 | let revealed = caretLine |
| 195 | var scriptExclusions: [Range<Int>] = [] | |
| 196 | for run in Presentation.styles(document.tree, in: whole, highlighter: Self.highlighter) { | |
| 197 | let clipped = NSIntersectionRange(NSRange(run.range), lines) | |
| 198 | guard clipped.length > 0 else { continue } | |
| 199 | if Presentation.skipsLeadingStars(run.role, indented: indented, hideStars: hideStars) { continue } | |
| 200 | if !showMarkup, Presentation.hidesWithMarkup(run.role, options: options), NSIntersectionRange(clipped, revealed).length == 0 { | |
| 201 | storage.addAttributes(theme.hidden, range: clipped) | |
| 202 | } else { | |
| 203 | theme.apply(run.role, to: storage, range: clipped) | |
| 220 | let (changes, scriptExclusions) = Presentation.styleChanges( | |
| 221 | document.tree, in: whole, highlighter: Self.highlighter, indented: indented, hideStars: hideStars, | |
| 222 | showMarkup: showMarkup, options: options, revealed: revealed.location..<NSMaxRange(revealed) | |
| 223 | ) | |
| 224 | for change in changes { | |
| 225 | switch change { | |
| 226 | case .indent(let line): storage.addAttribute(.paragraphStyle, value: paragraphStyle(line.firstLine, line.wrapped), range: NSRange(line.range)) | |
| 227 | case .role(let role, let range): theme.apply(role, to: storage, range: NSRange(range)) | |
| 228 | case .hidden(let range): storage.addAttributes(theme.hidden, range: NSRange(range)) | |
| 204 | 229 | } |
| 205 | if Presentation.excludesScripts(run.role) { scriptExclusions.append(run.range) } | |
| 206 | 230 | } |
| 207 | 231 | if theme.mixedPitch { |
| 208 | 232 | for prefix in Presentation.fixedPitchPrefixes(ns, in: whole) { |
| @@ -265,7 +289,7 @@ extension MobileEditor { | ||
| 265 | 289 | // The old line may have moved with edits since; restyle the line now at its start. |
| 266 | 290 | let old = revealedLine.flatMap { $0.location <= text.length ? text.lineRange(for: NSRange(location: $0.location, length: 0)) : nil } |
| 267 | 291 | revealedLine = line |
| 268 | for range in [old, line].compactMap({ $0 }) { | |
| 292 | for range in [old, line].compactMap({ $0 }) where range.location < styled.end { | |
| 269 | 293 | restyle(range.location..<NSMaxRange(range)) |
| 270 | 294 | } |
| 271 | 295 | } |
Sources/OrgstarMobile/MobileEditor.swift +10 −2
| @@ -144,6 +144,9 @@ final class MobileEditor: NSObject, DocumentBuffer { | ||
| 144 | 144 | static let imageCache = NSCache<NSString, UIImage>() |
| 145 | 145 | var loading = false |
| 146 | 146 | var restyleScheduled: Range<Int>? |
| 147 | /// Text before its end is styled; after it, the text waits for the background passes. | |
| 148 | var styled = StyledExtent() | |
| 149 | var stylingScheduled = false | |
| 147 | 150 | /// Narrowed table columns (`org-table-shrink`). |
| 148 | 151 | var shrunk = ShrunkColumns() |
| 149 | 152 | /// A command's edits being applied, which keep shrunk columns narrow. |
| @@ -284,7 +287,7 @@ final class MobileEditor: NSObject, DocumentBuffer { | ||
| 284 | 287 | textView.undoManager?.removeAllActions() |
| 285 | 288 | setFolds(fold) |
| 286 | 289 | } else if document.defaults != defaultsBefore { |
| 287 | restyle(0..<(document.text as NSString).length) | |
| 290 | restartStyling() | |
| 288 | 291 | } |
| 289 | 292 | return result |
| 290 | 293 | } |
| @@ -566,6 +569,8 @@ final class MobileEditor: NSObject, DocumentBuffer { | ||
| 566 | 569 | let old = range.location..<(range.location + range.length - delta) |
| 567 | 570 | let replacement = (textView.textStorage.string as NSString).substring(with: range) |
| 568 | 571 | let edit = TextEdit(range: old, replacement: replacement) |
| 572 | let oldTree = document.tree | |
| 573 | let oldText = document.text as NSString | |
| 569 | 574 | do { |
| 570 | 575 | try document.apply([edit], baseRevision: document.revision) |
| 571 | 576 | } catch { |
| @@ -574,13 +579,16 @@ final class MobileEditor: NSObject, DocumentBuffer { | ||
| 574 | 579 | load(textView.textStorage.string) |
| 575 | 580 | return |
| 576 | 581 | } |
| 582 | let newText = textView.textStorage.string as NSString | |
| 583 | styled.map(through: edit, in: newText) | |
| 584 | let affected = Presentation.restyleRange(for: edit, old: (oldTree, oldText), new: (document.tree, newText)) | |
| 577 | 585 | vim.changed(edit) |
| 578 | 586 | for table in shrunk.map(through: edit, in: textView.textStorage.string, command: commandEditing) { scheduleRestyle(table) } |
| 579 | 587 | fold = FoldState( |
| 580 | 588 | folds: Self.map(fold.folds, old, delta), bodyFolds: Self.map(fold.bodyFolds, old, delta), |
| 581 | 589 | wrapperFolds: Self.map(fold.wrapperFolds, old, delta) |
| 582 | 590 | ) |
| 583 | scheduleRestyle(range.location..<NSMaxRange(range)) | |
| 591 | scheduleRestyle(affected.lowerBound..<min(affected.upperBound, newText.length)) | |
| 584 | 592 | onChange?() |
| 585 | 593 | } |
| 586 | 594 | |
Tests/OrgPresentationTests/RestylingTests.swift added +245
| @@ -0,0 +1,245 @@ | ||
| 1 | import Foundation | |
| 2 | import OrgCore | |
| 3 | import Testing | |
| 4 | @testable import OrgPresentation | |
| 5 | ||
| 6 | struct 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 | ||
| 45 | struct 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 | ||
| 155 | struct 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 | ||
| 243 | private extension Range<Int> { | |
| 244 | func shifted(_ by: Int) -> Range<Int> { (lowerBound + by)..<(upperBound + by) } | |
| 245 | } | |