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