Sources/OrgPresentation/ReadingText.swift
140 lines · 8275 bytes
1import Foundation
2import OrgCore
3
4/// A range of a file to read rather than edit: its style runs as segments, with the brackets
5/// and targets of described links hidden (`org-link-descriptive`) and folded drawers shown as
6/// their first line and `…`, as the editor shows them.
7public enum ReadingText {
8 public struct Segment: Sendable, Equatable {
9 public var text: String
10 public var roles: Set<StyleRole>
11 /// The link this text belongs to.
12 public var link: OrgLink?
13 /// Where the text starts in the file.
14 public var offset: Int
15 /// A pretty sub/superscript's body: true raised, false lowered.
16 public var superscript: Bool?
17 /// A drawer's opening line, and a folded one's `…`: where the hidden range they fold
18 /// and unfold starts.
19 public var toggles: Int?
20 }
21
22 /// How the text shows, as the editor's display settings make it.
23 public struct Display: Sendable {
24 /// Link brackets and targets, and emphasis markers, shown; no pretty entities.
25 public var showMarkup = false
26 /// `org-hide-emphasis-markers`, `org-pretty-entities` and its braces.
27 public var options = EditingOptions.org
28 /// Colors code in src blocks.
29 public var highlighter: (any CodeHighlighter)?
30
31 public init(showMarkup: Bool = false, options: EditingOptions = .org, highlighter: (any CodeHighlighter)? = nil) {
32 self.showMarkup = showMarkup
33 self.options = options
34 self.highlighter = highlighter
35 }
36 }
37
38 /// `folded` are drawers' and blocks' hidden ranges (`Wrapper.hidden`); `open` are those of
39 /// unfolded ones whose opening line folds them.
40 public static func segments(
41 _ tree: OrgTree, in range: Range<Int>, folded: [Range<Int>] = [], open: [Range<Int>] = [], display: Display = Display()
42 ) -> [Segment] {
43 let text = tree.text as NSString
44 // A fold hides from the end of the opening line through the closing line, so the
45 // marker sits on the opening line.
46 let folds = folded.compactMap { r -> Range<Int>? in
47 guard r.lowerBound > range.lowerBound, r.lowerBound <= range.upperBound else { return nil }
48 let end = r.upperBound > r.lowerBound && r.upperBound <= text.length && text.character(at: r.upperBound - 1) == 10 ? r.upperBound - 1 : r.upperBound
49 return (r.lowerBound - 1)..<min(end, range.upperBound)
50 }
51 // Styled only where shown: a folded drawer can hold most of a section.
52 var visible: [Range<Int>] = []
53 var from = range.lowerBound
54 for fold in folds.sorted(by: { $0.lowerBound < $1.lowerBound }) where fold.upperBound > from {
55 if fold.lowerBound > from { visible.append(from..<fold.lowerBound) }
56 from = fold.upperBound
57 }
58 if from < range.upperBound || visible.isEmpty { visible.append(from..<max(from, range.upperBound)) }
59 let runs = visible.flatMap { Presentation.styles(tree, in: $0, highlighter: display.highlighter) }
60 var hidden = runs.filter { !display.showMarkup && Presentation.hidesWithMarkup($0.role, options: display.options) }.map(\.range) + folds
61 // `org-pretty-entities`: an entity's last character shows its character, the rest hidden.
62 var replaced: [Int: String] = [:]
63 var scripts: [(range: Range<Int>, superscript: Bool)] = []
64 if !display.showMarkup, display.options.prettyEntities {
65 let blocks = Presentation.shadedBlocks(tree)
66 let exclusions = runs.filter { Presentation.excludesScripts($0.role) }.map(\.range)
67 let pretty = visible.flatMap { part in
68 Presentation.prettyRuns(
69 text, in: part, revealedLine: nil, inBlock: { offset in blocks.contains { $0.contains(offset) } },
70 scriptExclusions: exclusions, subSuperscriptsNeedBraces: display.options.subSuperscriptsNeedBraces
71 )
72 }
73 for (lineStart, run) in pretty {
74 switch run {
75 case .entity(let r, let shown):
76 let last = lineStart + r.upperBound - 1
77 hidden.append((lineStart + r.lowerBound)..<last)
78 replaced[last] = shown
79 case .script(let markers, let body, let superscript):
80 hidden += markers.map { (lineStart + $0.lowerBound)..<(lineStart + $0.upperBound) }
81 scripts.append(((lineStart + body.lowerBound)..<(lineStart + body.upperBound), superscript))
82 }
83 }
84 }
85 // Opening lines that fold or unfold, a wider target than a `…`.
86 let lineStart = { (end: Int) in text.lineRange(for: NSRange(location: end, length: 0)).location }
87 let openings = folds.map { (line: lineStart($0.lowerBound)..<$0.lowerBound, start: $0.lowerBound + 1) }
88 + open.filter { $0.lowerBound > range.lowerBound && $0.lowerBound <= range.upperBound }
89 .map { (line: lineStart($0.lowerBound - 1)..<($0.lowerBound - 1), start: $0.lowerBound) }
90 var bounds: Set<Int> = [range.lowerBound, range.upperBound]
91 for opening in openings { bounds.formUnion([max(range.lowerBound, opening.line.lowerBound), opening.line.upperBound]) }
92 let replacedRanges = replaced.keys.map { $0..<($0 + 1) }
93 for r in runs.map(\.range) + hidden + replacedRanges + scripts.map(\.range) {
94 bounds.insert(max(range.lowerBound, min(range.upperBound, r.lowerBound)))
95 bounds.insert(max(range.lowerBound, min(range.upperBound, r.upperBound)))
96 }
97 let points = bounds.sorted()
98 var segments: [Segment] = []
99 func append(_ segment: Segment) {
100 if var last = segments.last, last.roles == segment.roles, last.link == segment.link, last.superscript == segment.superscript, last.toggles == segment.toggles,
101 last.offset + (last.text as NSString).length == segment.offset {
102 last.text += segment.text
103 segments[segments.count - 1] = last
104 } else {
105 segments.append(segment)
106 }
107 }
108 // What covers each interval between consecutive points, marked range by range rather
109 // than tested interval by interval, which grows with the square of a long section.
110 let intervals = max(points.count - 1, 0)
111 var position: [Int: Int] = [:]
112 for (k, point) in points.enumerated() { position[point] = k }
113 func covered(_ r: Range<Int>) -> Range<Int> {
114 let lo = position[max(range.lowerBound, min(range.upperBound, r.lowerBound))]!
115 let hi = position[max(range.lowerBound, min(range.upperBound, r.upperBound))]!
116 return lo..<max(lo, hi)
117 }
118 var rolesAt = [Set<StyleRole>](repeating: [], count: intervals)
119 for run in runs { for k in covered(run.range) { rolesAt[k].insert(run.role) } }
120 var hiddenAt = [Bool](repeating: false, count: intervals)
121 for r in hidden { for k in covered(r) { hiddenAt[k] = true } }
122 var scriptAt = [Bool?](repeating: nil, count: intervals)
123 for script in scripts { for k in covered(script.range) where scriptAt[k] == nil { scriptAt[k] = script.superscript } }
124 let foldStarts = Set(folds.map(\.lowerBound))
125 for (k, (a, b)) in zip(points, points.dropFirst()).enumerated() {
126 if foldStarts.contains(a) {
127 segments.append(Segment(text: "…", roles: [.metadata], link: nil, offset: a, toggles: a + 1))
128 }
129 if hiddenAt[k] { continue }
130 let roles = rolesAt[k]
131 let link = roles.contains(.link) ? Links.link(at: a, text: tree.text, tree: tree)?.link : nil
132 let superscript = scriptAt[k]
133 let shown = replaced[a] ?? text.substring(with: NSRange(location: a, length: b - a))
134 let toggles = openings.first { $0.line.contains(a) }?.start
135 let segment = Segment(text: shown, roles: roles, link: link, offset: a, superscript: superscript, toggles: toggles)
136 if replaced[a] != nil { segments.append(segment) } else { append(segment) }
137 }
138 return segments
139 }
140}