Sources/OrgPresentation/Presentation.swift
284 lines · 13544 bytes
1import OrgCore
2
3/// What a range of text is, for styling. Platform adapters map roles to attributes.
4public enum StyleRole: Hashable, Sendable {
5 /// A whole heading line.
6 case heading(level: Int)
7 /// All stars of a heading but the last, hidden as in `org-hide-leading-stars`.
8 case leadingStars
9 case todo, done, priority, tags
10 case bold, italic, underline, strikeThrough, verbatim, code
11 /// Emphasis markers.
12 case markup
13 case link
14 /// Brackets and the target of a described link.
15 case linkMarkup
16 case timestamp, footnote, cookie, target, macro, latex, inlineSource
17 case comment, keyword
18 /// Planning lines, drawers, property drawers, clock lines.
19 case metadata
20 case block, blockDelimiter, table, rule
21 /// Code in a src block, by what the language's grammar says it is.
22 case syntax(SyntaxCategory)
23}
24
25/// Kinds of code token, from tree-sitter highlight capture names.
26public enum SyntaxCategory: String, Hashable, Sendable, CaseIterable {
27 case keyword, string, comment, function, type, number, constant, variable, property, `operator`
28 case punctuation, attribute, tag, escape, label
29
30 /// The category for a capture name such as `keyword.control` or `string.special`.
31 public init?(capture name: String) {
32 let head = name.split(separator: ".").first.map(String.init) ?? name
33 switch head {
34 case "keyword", "conditional", "repeat", "include", "exception", "storageclass": self = .keyword
35 case "string", "character": self = name.hasPrefix("string.escape") ? .escape : .string
36 case "comment": self = .comment
37 case "function", "method": self = .function
38 case "type", "constructor", "module", "namespace": self = .type
39 case "number", "float": self = .number
40 case "constant", "boolean": self = .constant
41 case "variable", "parameter": self = .variable
42 case "property", "field": self = .property
43 case "operator": self = .operator
44 case "punctuation": self = .punctuation
45 case "attribute", "annotation", "decorator": self = .attribute
46 case "tag": self = .tag
47 case "escape": self = .escape
48 case "label": self = .label
49 default: return nil
50 }
51 }
52}
53
54extension SyntaxCategory {
55 /// The theme color for this kind of token; nil for those drawn in the text color.
56 public var themeKey: String? {
57 switch self {
58 case .keyword: "syntax-keyword"
59 case .string: "syntax-string"
60 case .comment: "syntax-comment"
61 case .function: "syntax-function"
62 case .type: "syntax-type"
63 case .number, .constant, .escape: "syntax-number"
64 case .property, .attribute, .tag: "syntax-property"
65 case .label: "syntax-label"
66 case .variable, .operator, .punctuation: nil
67 }
68 }
69}
70
71/// Highlights source code; the apps supply tree-sitter's (OrgHighlight).
72public protocol CodeHighlighter: Sendable {
73 /// Categories for ranges of `code`, in UTF-16 offsets; later runs win over earlier ones.
74 /// Empty for languages it doesn't know.
75 func highlights(language: String, code: String) -> [(range: Range<Int>, category: SyntaxCategory)]
76}
77
78public struct StyleRun: Sendable, Equatable {
79 public let range: Range<Int>
80 public let role: StyleRole
81}
82
83/// org-indent: how many columns a run of whole lines starts in.
84public struct IndentRun: Sendable, Equatable {
85 public let range: Range<Int>
86 public let firstLine: Int
87 /// Continuation lines of a wrapped paragraph.
88 public let wrapped: Int
89}
90
91public enum Presentation {
92 /// Style runs for nodes and tokens overlapping `range`, outer before inner, so applying
93 /// them in order lets inner roles win.
94 public static func styles(_ tree: OrgTree, in range: Range<Int>, highlighter: (any CodeHighlighter)? = nil) -> [StyleRun] {
95 var runs: [StyleRun] = []
96 visit(tree.root, range, tree.settings, highlighter, &runs)
97 return runs
98 }
99
100 /// Runs for the code inside a src block, from `highlighter`.
101 static func sourceRuns(_ node: SyntaxNode, _ highlighter: any CodeHighlighter) -> [StyleRun] {
102 let lines = node.tokens.filter { $0.kind == .text }
103 guard lines.count >= 2, let first = lines.first, let last = lines.last,
104 let match = first.text.firstMatch(of: /^[ \t]*#\+(?i:begin_src)[ \t]+(\S+)/) else { return [] }
105 let language = String(match.1)
106 let start = first.range.upperBound + 1
107 let end = last.range.lowerBound
108 guard end > start else { return [] }
109 let utf16 = node.text.utf16
110 let lower = utf16.index(utf16.startIndex, offsetBy: start - node.range.lowerBound)
111 let upper = utf16.index(utf16.startIndex, offsetBy: end - node.range.lowerBound)
112 let code = String(node.text[lower..<upper])
113 return highlighter.highlights(language: language, code: code).map {
114 StyleRun(range: ($0.range.lowerBound + start)..<($0.range.upperBound + start), role: .syntax($0.category))
115 }
116 }
117
118 private static func visit(_ node: SyntaxNode, _ range: Range<Int>, _ settings: OrgSettings, _ highlighter: (any CodeHighlighter)?, _ runs: inout [StyleRun]) {
119 if let role = role(of: node) { runs.append(StyleRun(range: node.range, role: role)) }
120 switch node.kind {
121 case .heading:
122 for token in node.tokens {
123 switch token.kind {
124 case .stars where token.range.count > 1:
125 runs.append(StyleRun(range: token.range.lowerBound..<(token.range.upperBound - 1), role: .leadingStars))
126 case .todoKeyword:
127 runs.append(StyleRun(range: token.range, role: settings.isDone(token.text) ? .done : .todo))
128 case .priority:
129 runs.append(StyleRun(range: token.range, role: .priority))
130 case .tags:
131 runs.append(StyleRun(range: token.range, role: .tags))
132 default:
133 break
134 }
135 }
136 case .link:
137 let described = node.children.contains { $0.kind == .linkDescription }
138 for token in node.tokens where token.kind == .marker || (described && token.kind == .linkPath) {
139 runs.append(StyleRun(range: token.range, role: .linkMarkup))
140 }
141 case .bold, .italic, .underline, .strikeThrough, .verbatim, .code:
142 for token in node.tokens where token.kind == .marker {
143 runs.append(StyleRun(range: token.range, role: .markup))
144 }
145 case .block, .dynamicBlock:
146 let lines = node.tokens.filter { $0.kind == .text }
147 for token in [lines.first, lines.count > 1 ? lines.last : nil].compactMap({ $0 }) {
148 runs.append(StyleRun(range: token.range, role: .blockDelimiter))
149 }
150 if let highlighter { runs += sourceRuns(node, highlighter) }
151 default:
152 break
153 }
154 for child in node.children(overlapping: range) {
155 visit(child, range, settings, highlighter, &runs)
156 }
157 }
158
159 static func role(of node: SyntaxNode) -> StyleRole? {
160 switch node.kind {
161 case .heading: .heading(level: node.tokens.first { $0.kind == .stars }?.text.count ?? 1)
162 case .bold: .bold
163 case .italic: .italic
164 case .underline: .underline
165 case .strikeThrough: .strikeThrough
166 case .verbatim: .verbatim
167 case .code: .code
168 case .link: .link
169 case .timestamp: .timestamp
170 case .footnoteReference, .footnoteDefinition: .footnote
171 case .statisticsCookie: .cookie
172 case .target, .radioTarget: .target
173 case .macro: .macro
174 case .latexFragment, .latexEnvironment: .latex
175 case .inlineSourceBlock, .inlineBabelCall, .exportSnippet: .inlineSource
176 case .citation: .link
177 case .itemTag: .bold
178 case .diarySexp: .timestamp
179 case .comment: .comment
180 case .keyword, .affiliatedKeyword: .keyword
181 case .planning, .propertyDrawer, .drawer, .clock: .metadata
182 case .block, .dynamicBlock, .fixedWidth: .block
183 case .table, .tableEl: .table
184 case .horizontalRule: .rule
185 default: nil
186 }
187 }
188
189 /// Heading lines start at column 0, with wrapped title lines under the title; a section's
190 /// own body starts one column past its stars.
191 public static func indents(_ tree: OrgTree, in range: Range<Int>) -> [IndentRun] {
192 var runs: [IndentRun] = []
193 collectIndents(tree.root, range, &runs)
194 return runs
195 }
196
197 private static func collectIndents(_ node: SyntaxNode, _ range: Range<Int>, _ runs: inout [IndentRun]) {
198 for section in node.children(overlapping: range) where section.kind == .section {
199 guard let heading = section.firstChild(.heading) else { continue }
200 let level = heading.tokens.first { $0.kind == .stars }?.text.count ?? 1
201 runs.append(IndentRun(range: heading.range, firstLine: 0, wrapped: level + 1))
202 let bodyEnd = section.firstChild(.section)?.range.lowerBound ?? section.range.upperBound
203 if heading.range.upperBound < bodyEnd {
204 runs.append(IndentRun(range: heading.range.upperBound..<bodyEnd, firstLine: level + 1, wrapped: level + 1))
205 }
206 collectIndents(section, range, &runs)
207 }
208 }
209
210 /// Blocks and fixed-width areas, drawn on a shaded band the width of the view. Sorted.
211 public static func shadedBlocks(_ tree: OrgTree) -> [Range<Int>] {
212 var ranges: [Range<Int>] = []
213 func walk(_ node: SyntaxNode) {
214 for child in node.children {
215 switch child.kind {
216 case .block, .dynamicBlock, .fixedWidth:
217 // Without the blank lines org counts as part of the element.
218 let text = child.text
219 let trimmed = text.utf16.count - String(text.reversed().prefix { $0.isWhitespace }).utf16.count
220 ranges.append(child.range.lowerBound..<(child.range.lowerBound + trimmed))
221 case .paragraph, .table, .heading, .planning, .propertyDrawer, .drawer, .keyword, .comment: continue
222 default: walk(child)
223 }
224 }
225 }
226 walk(tree.root)
227 return ranges
228 }
229
230 /// Ranges to hide. A heading in `folds` hides everything after its line to the end of its
231 /// section; one in `bodyFolds` hides only its own body, up to its first child heading.
232 /// Sorted, without nested duplicates.
233 /// A drawer or block in `wrapperFolds` hides the lines after its opening line.
234 public static func hiddenRanges(_ tree: OrgTree, folds: Set<Int>, bodyFolds: Set<Int> = [], wrapperFolds: Set<Int> = []) -> [Range<Int>] {
235 hiddenRanges(tree, folds: folds, bodyFolds: bodyFolds, wrapperRanges: wrapperFolds.compactMap { Wrappers.starting(at: $0, in: tree)?.hidden })
236 }
237
238 /// The same, with the folded drawers' and blocks' hidden ranges already found.
239 public static func hiddenRanges(_ tree: OrgTree, folds: Set<Int>, bodyFolds: Set<Int>, wrapperRanges: [Range<Int>]) -> [Range<Int>] {
240 guard !folds.isEmpty || !bodyFolds.isEmpty || !wrapperRanges.isEmpty else { return [] }
241 var ranges: [Range<Int>] = []
242 if !folds.isEmpty || !bodyFolds.isEmpty { collectHidden(tree.root, folds, bodyFolds, &ranges) }
243 guard !wrapperRanges.isEmpty else { return ranges }
244 ranges += wrapperRanges
245 ranges.sort { $0.lowerBound != $1.lowerBound ? $0.lowerBound < $1.lowerBound : $0.upperBound > $1.upperBound }
246 var merged: [Range<Int>] = []
247 for range in ranges where !(merged.last.map { $0.upperBound >= range.upperBound } ?? false) { merged.append(range) }
248 return merged
249 }
250
251 private static func collectHidden(_ node: SyntaxNode, _ folds: Set<Int>, _ bodyFolds: Set<Int>, _ ranges: inout [Range<Int>]) {
252 for section in node.children where section.kind == .section {
253 guard let heading = section.firstChild(.heading) else { continue }
254 let start = heading.range.lowerBound
255 if folds.contains(start) {
256 if heading.range.upperBound < section.range.upperBound {
257 ranges.append(heading.range.upperBound..<section.range.upperBound)
258 }
259 continue
260 }
261 if bodyFolds.contains(start) {
262 let bodyEnd = section.firstChild(.section)?.range.lowerBound ?? section.range.upperBound
263 if heading.range.upperBound < bodyEnd { ranges.append(heading.range.upperBound..<bodyEnd) }
264 }
265 collectHidden(section, folds, bodyFolds, &ranges)
266 }
267 }
268
269 /// Start offset of the heading whose line contains `offset`.
270 public static func heading(containing offset: Int, in tree: OrgTree) -> Int? {
271 var node = tree.root
272 while let child = node.child(containing: offset) {
273 if child.kind == .heading { return child.range.lowerBound }
274 guard child.kind == .section || child.kind == .zerothSection else { return nil }
275 node = child
276 }
277 return nil
278 }
279
280 /// Start offsets of every heading, for folding everything.
281 public static func headings(_ tree: OrgTree) -> [Int] {
282 tree.root.descendants().filter { $0.kind == .heading }.map(\.range.lowerBound)
283 }
284}