Sources/OrgCore/Semantic/DocumentModel.swift

5eef7a168632da902fdd0979d57258320e4fdfc2
orgstar/Sources/OrgCore/Semantic/DocumentModel.swift history · blame · raw

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