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