Sources/OrgCore/Semantic/DocumentModel.swift

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

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