Sources/OrgCore/Semantic/DocumentModel.swift
294 lines · 14040 bytes
1import Foundation
2
3/// Typed facts read from one parsed document. Built once per tree; commands and the index read
4/// this rather than raw text.
5public struct DocumentModel: Sendable {
6 public let settings: SemanticSettings
7 public let orgSettings: OrgSettings
8 public private(set) var headings: [HeadingInfo] = []
9 public private(set) var fileTags: [String] = []
10 /// `#+PROPERTY:` lines in order.
11 public private(set) var fileProperties: [Property] = []
12 public private(set) var tables: [TableModel] = []
13 public private(set) var srcBlocks: [SrcBlockInfo] = []
14
15 /// Always inherited, whatever the inheritance setting.
16 static let alwaysInherited: Set<String> = ["CATEGORY", "ARCHIVE", "COLUMNS", "LOGGING"]
17 /// Identify one heading, so never inherited.
18 static let neverInherited: Set<String> = ["ID", "CUSTOM_ID"]
19
20 private typealias PendingBlock = (node: SyntaxNode, heading: Int?, affiliated: [SyntaxNode])
21
22 public init(tree: OrgTree, settings: SemanticSettings = .default) {
23 self.settings = settings
24 self.orgSettings = tree.settings
25 for (key, value) in SetupFile.keywords(tree.settings.setupKeywords) { fileKeyword(key, value.trimmingCharacters(in: .whitespaces)) }
26 var pending: [PendingBlock] = []
27 walk(tree.root, heading: nil, pending: &pending)
28 // Header arguments depend on file and heading properties, so blocks resolve last.
29 srcBlocks = pending.map { srcBlock($0.node, heading: $0.heading, affiliated: $0.affiliated) }
30 }
31
32 // MARK: - Queries
33
34 /// Ancestor indexes of a heading, outermost first.
35 public func ancestors(of index: Int) -> [Int] {
36 var result: [Int] = []
37 var current = headings[index].parent
38 while let parent = current {
39 result.insert(parent, at: 0)
40 current = headings[parent].parent
41 }
42 return result
43 }
44
45 /// Titles from the outermost ancestor down to the heading itself.
46 public func outlinePath(of index: Int) -> [String] {
47 (ancestors(of: index) + [index]).map { headings[$0].title }
48 }
49
50 public func inherits(_ key: String) -> Bool {
51 let key = key.uppercased()
52 if Self.neverInherited.contains(key) { return false }
53 if Self.alwaysInherited.contains(key) || key.hasPrefix("HEADER-ARGS") { return true }
54 switch settings.propertyInheritance {
55 case .none: return false
56 case .all: return true
57 case .only(let keys): return keys.contains(key)
58 }
59 }
60
61 /// The value of `key` for a heading, or for the file when `index` is nil. Inherited keys
62 /// start from `#+PROPERTY` and walk down the ancestors; `KEY+` lines append with a space.
63 public func property(_ key: String, of index: Int?) -> Resolved<String>? {
64 let key = key.uppercased()
65 var layers: [(entries: [Property], source: ValueSource)] = []
66 if let index {
67 if inherits(key) {
68 layers.append((fileProperties, .file))
69 layers += ancestors(of: index).map { (headings[$0].properties, .heading($0)) }
70 }
71 layers.append((headings[index].properties, .heading(index)))
72 } else {
73 layers.append((fileProperties, .file))
74 }
75 var result: Resolved<String>?
76 for layer in layers {
77 for entry in layer.entries where entry.key.uppercased() == key {
78 if entry.additive, let current = result {
79 result = Resolved(current.value + " " + entry.value, layer.source)
80 } else {
81 result = Resolved(entry.value, layer.source)
82 }
83 }
84 }
85 return result
86 }
87
88 /// Inherited tags first (file tags, then ancestors outermost first), then the heading's own.
89 /// A tag the heading has itself counts as its own.
90 public func tags(of index: Int) -> [Resolved<String>] {
91 let local = headings[index].localTags
92 var inherited: [Resolved<String>] = []
93 if settings.tagInheritance {
94 let layers = [(fileTags, ValueSource.file)] + ancestors(of: index).map { (headings[$0].localTags, ValueSource.heading($0)) }
95 for (tags, source) in layers {
96 for tag in tags where !settings.tagsExcludedFromInheritance.contains(tag)
97 && !local.contains(tag) && !inherited.contains(where: { $0.value == tag }) {
98 inherited.append(Resolved(tag, source))
99 }
100 }
101 }
102 var own: [Resolved<String>] = []
103 for tag in local where !own.contains(where: { $0.value == tag }) {
104 own.append(Resolved(tag, .heading(index)))
105 }
106 return inherited + own
107 }
108
109 // MARK: - Building
110
111 private mutating func walk(_ node: SyntaxNode, heading: Int?, pending: inout [PendingBlock]) {
112 var previous: SyntaxNode?
113 var affiliated: [SyntaxNode] = []
114 for child in node.children {
115 // Blank lines between nodes detach affiliated keywords.
116 if let previous, previous.range.upperBound != child.range.lowerBound { affiliated = [] }
117 switch child.kind {
118 case .section:
119 section(child, parent: heading, pending: &pending)
120 case .heading, .affiliatedKeyword:
121 break
122 case .planning:
123 if let heading { planning(child, heading) }
124 case .propertyDrawer:
125 let properties = child.children.filter { $0.kind == .nodeProperty }.compactMap { Property(line: $0.text) }
126 // The file's own drawer comes after its #+PROPERTY lines, as org reads them.
127 if let heading { headings[heading].properties += properties } else { fileProperties += properties }
128 case .clock:
129 if let heading, let clock = clock(child) { headings[heading].clocks.append(clock) }
130 case .timestamp:
131 if let heading, let stamp = Timestamp.parse(child.text) { headings[heading].timestamps.append(stamp) }
132 case .link:
133 if let heading { headings[heading].links.append(linkTarget(child)) }
134 case .keyword:
135 fileKeyword(child)
136 case .table:
137 tables.append(TableModel(node: child, heading: heading))
138 walk(child, heading: heading, pending: &pending)
139 case .block:
140 if Self.isSrcBlock(child) { pending.append((child, heading, affiliated)) }
141 default:
142 walk(child, heading: heading, pending: &pending)
143 }
144 affiliated = child.kind == .affiliatedKeyword ? affiliated + [child] : []
145 previous = child
146 }
147 }
148
149 private mutating func section(_ node: SyntaxNode, parent: Int?, pending: inout [PendingBlock]) {
150 guard let headingNode = node.children.first(where: { $0.kind == .heading }) else { return }
151 let index = headings.count
152 let tokens = headingNode.tokens
153 let todo = tokens.first { $0.kind == .todoKeyword }?.text
154 let title = headingNode.children.first { $0.kind == .title }
155 headings.append(HeadingInfo(
156 sectionRange: node.range,
157 headingRange: headingNode.range,
158 level: tokens.first { $0.kind == .stars }?.text.count ?? 0,
159 parent: parent,
160 todo: todo,
161 isDone: todo.map(orgSettings.isDone) ?? false,
162 priority: tokens.first { $0.kind == .priority }.map { String($0.text.dropFirst(2).dropLast()) },
163 title: title?.text ?? "",
164 localTags: tokens.first { $0.kind == .tags }.map { $0.text.split(separator: ":").map(String.init) } ?? [],
165 properties: [], scheduled: nil, deadline: nil, closed: nil, clocks: [], timestamps: [], links: []
166 ))
167 if let title { walk(title, heading: index, pending: &pending) }
168 walk(node, heading: index, pending: &pending)
169 }
170
171 /// Each timestamp belongs to the keyword just before it.
172 private mutating func planning(_ node: SyntaxNode, _ heading: Int) {
173 let text = node.text
174 for stampNode in node.children where stampNode.kind == .timestamp {
175 guard let stamp = Timestamp.parse(stampNode.text) else { continue }
176 let end = String.Index(utf16Offset: stampNode.offset - node.offset, in: text)
177 let before = text[..<end].trimmingCharacters(in: .whitespaces)
178 if before.hasSuffix("SCHEDULED:") {
179 headings[heading].scheduled = stamp
180 } else if before.hasSuffix("DEADLINE:") {
181 headings[heading].deadline = stamp
182 } else if before.hasSuffix("CLOSED:") {
183 headings[heading].closed = stamp
184 }
185 }
186 }
187
188 private func clock(_ node: SyntaxNode) -> Clock? {
189 guard let stampNode = node.children.first(where: { $0.kind == .timestamp }),
190 let stamp = Timestamp.parse(stampNode.text) else { return nil }
191 var minutes: Int?
192 if let arrow = node.text.range(of: "=>") {
193 let parts = node.text[arrow.upperBound...].trimmingCharacters(in: .whitespacesAndNewlines).split(separator: ":")
194 if parts.count == 2, let hours = Int(parts[0]), let mins = Int(parts[1]) { minutes = hours * 60 + mins }
195 }
196 return Clock(start: stamp.start, end: stamp.end, minutes: minutes)
197 }
198
199 private func linkTarget(_ node: SyntaxNode) -> String {
200 if let path = node.tokens.first(where: { $0.kind == .linkPath }) { return path.text }
201 let text = node.text
202 if text.hasPrefix("<"), text.hasSuffix(">") { return String(text.dropFirst().dropLast()) }
203 return text
204 }
205
206 private mutating func fileKeyword(_ node: SyntaxNode) {
207 let text = node.text.trimmingCharacters(in: .whitespacesAndNewlines)
208 guard let colon = text.firstIndex(of: ":") else { return }
209 fileKeyword(text[text.index(text.startIndex, offsetBy: 2)..<colon].uppercased(), text[text.index(after: colon)...].trimmingCharacters(in: .whitespaces))
210 }
211
212 private mutating func fileKeyword(_ key: String, _ value: String) {
213 switch key {
214 case "FILETAGS":
215 fileTags += value.split(whereSeparator: { $0 == ":" || $0.isWhitespace }).map(String.init)
216 case "PROPERTY":
217 let parts = value.split(maxSplits: 1, whereSeparator: \.isWhitespace)
218 guard var name = parts.first.map(String.init) else { return }
219 let additive = name.hasSuffix("+")
220 if additive { name.removeLast() }
221 fileProperties.append(Property(key: name, value: parts.count > 1 ? String(parts[1]) : "", additive: additive))
222 default:
223 break
224 }
225 }
226
227 // MARK: - Source blocks
228
229 static func isSrcBlock(_ node: SyntaxNode) -> Bool {
230 node.text.drop { $0 == " " || $0 == "\t" }.lowercased().hasPrefix("#+begin_src")
231 }
232
233 private func srcBlock(_ node: SyntaxNode, heading: Int?, affiliated: [SyntaxNode]) -> SrcBlockInfo {
234 let raw = splitRawLines(node.text)
235 let beginLine = raw[0].content.drop { $0 == " " || $0 == "\t" }.dropFirst("#+begin_src".count)
236 let words = beginLine.split(whereSeparator: \.isWhitespace)
237 var language: String?
238 var switches: [String] = []
239 var rest = words[...]
240 if let first = rest.first, !first.hasPrefix("-"), !first.hasPrefix("+"), !first.hasPrefix(":") {
241 language = String(first)
242 rest = rest.dropFirst()
243 }
244 while let word = rest.first, !word.hasPrefix(":") {
245 switches.append(String(word))
246 rest = rest.dropFirst()
247 }
248 let body = raw.dropFirst().dropLast().map { String($0.content) + String($0.ending) }.joined()
249
250 var name: String?
251 var headerLines: [String] = []
252 for keyword in affiliated {
253 let text = keyword.text.trimmingCharacters(in: .whitespacesAndNewlines)
254 let value = SettingsScanner.keywordValue(text[...]).trimmingCharacters(in: .whitespaces)
255 if text.uppercased().hasPrefix("#+NAME:") { name = value }
256 if text.uppercased().hasPrefix("#+HEADER:") { headerLines.append(value) }
257 }
258
259 var arguments = HeaderArguments.defaults.mapValues { Resolved($0, .defaults) }
260 var keys = ["header-args"]
261 if let language { keys.append("header-args:\(language)") }
262 for key in keys {
263 for pair in headerArgumentLayers(key, heading: heading) {
264 arguments[pair.key] = Resolved(pair.value, pair.source)
265 }
266 }
267 for line in headerLines + [rest.joined(separator: " ")] {
268 for pair in HeaderArguments.parse(line) {
269 arguments[pair.key] = Resolved(pair.value, .element)
270 }
271 }
272 return SrcBlockInfo(
273 range: node.range, heading: heading, name: name, language: language,
274 switches: switches, body: body, headerArguments: arguments
275 )
276 }
277
278 /// `header-args` pairs from `#+PROPERTY` down to the heading. As in org, a plain property
279 /// replaces everything above it; `header-args+` adds to it.
280 private func headerArgumentLayers(_ key: String, heading: Int?) -> [(key: String, value: String, source: ValueSource)] {
281 var layers: [(entries: [Property], source: ValueSource)] = [(fileProperties, .file)]
282 if let heading {
283 layers += (ancestors(of: heading) + [heading]).map { (headings[$0].properties, .heading($0)) }
284 }
285 var pairs: [(key: String, value: String, source: ValueSource)] = []
286 for layer in layers {
287 for entry in layer.entries where entry.key.lowercased() == key {
288 let parsed = HeaderArguments.parse(entry.value).map { (key: $0.key, value: $0.value, source: layer.source) }
289 pairs = entry.additive ? pairs + parsed : parsed
290 }
291 }
292 return pairs
293 }
294}