Sources/OrgCore/Agenda/AgendaSource.swift

359666677e3403c6c38599c91ff884b7aa3787cd
orgstar/Sources/OrgCore/Agenda/AgendaSource.swift history · blame · raw

256 lines · 12666 bytes

  1import Foundation
  2
  3/// What the agenda needs from one file, read once from its text: headings with their planning,
  4/// and the active timestamps and date ranges org's agenda would consider. Positions are UTF-16.
  5public struct AgendaSource: Sendable {
  6    public let path: String
  7
  8    struct Heading: Sendable {
  9        /// Start of the heading line.
 10        let start: Int
 11        let level: Int
 12        /// In an archived or commented tree, which the agenda skips.
 13        let skipped: Bool
 14        /// The title without keyword, priority and tags (`ITEM`).
 15        let title: String
 16        /// The priority cookie's value.
 17        let priority: String?
 18        let localTags: [String]
 19        /// Upper-cased keys of the entry's own drawer.
 20        let properties: [String: String]
 21        /// Planning timestamps with brackets, for property matches.
 22        let planning: [String: String]
 23        /// The first active and inactive timestamps in the entry (`TIMESTAMP`, `TIMESTAMP_IA`).
 24        let firstActive: String?
 25        let firstInactive: String?
 26        /// The heading line without its newline.
 27        let line: String
 28        /// The line after the stars.
 29        let head: String
 30        let todo: String?
 31        let isDone: Bool
 32        /// Inherited tags first; the flag marks inherited ones.
 33        let tags: [(name: String, inherited: Bool)]
 34        let category: String
 35        /// The planning timestamp without brackets, and the position of its `<`.
 36        let scheduled: (raw: String, offset: Int)?
 37        let deadline: (raw: String, offset: Int)?
 38    }
 39
 40    struct Stamp: Sendable {
 41        let offset: Int
 42        let heading: Int
 43        /// From the `<` to the end of the line.
 44        let rest: String
 45    }
 46
 47    struct Block: Sendable {
 48        let start: String
 49        let end: String
 50        /// End of the range; org's marker sits there.
 51        let marker: Int
 52        let heading: Int
 53    }
 54
 55    let headings: [Heading]
 56    let stamps: [Stamp]
 57    let blocks: [Block]
 58    /// The file's TODO keywords, active and done.
 59    let keywords: [String]
 60    let priorities: Priorities
 61
 62    public init(path: String, text: String, defaults: OrgSettings = .default) {
 63        self.path = path
 64        let tree = OrgParser.parse(text, defaults: defaults)
 65        let model = DocumentModel(tree: tree)
 66        let ns = text as NSString
 67        let settings = tree.settings
 68        keywords = settings.todoSequences.flatMap { $0.active.map(\.name) + $0.done.map(\.name) }
 69        priorities = settings.priorities
 70
 71        var stampsByHeading: [Int: [String]] = [:]
 72        var headingIndex = -1
 73        func collect(_ node: SyntaxNode) {
 74            for child in node.children {
 75                if child.kind == .heading { headingIndex += 1 }
 76                if child.kind == .timestamp, headingIndex >= 0 {
 77                    stampsByHeading[headingIndex, default: []].append(child.text)
 78                } else if child.kind != .block, child.kind != .planning {
 79                    collect(child)
 80                }
 81            }
 82        }
 83        collect(tree.root)
 84        func sectionStamps(_ index: Int) -> [String] { stampsByHeading[index] ?? [] }
 85
 86        var keywordCategory: String?
 87        var srcBodies: [Range<Int>] = []
 88        var planningLines: [Range<Int>] = []
 89        var timestampNodes: [Int] = []
 90        var propertyLines: [Range<Int>] = []
 91        func walk(_ node: SyntaxNode) {
 92            for child in node.children {
 93                switch child.kind {
 94                case .keyword:
 95                    let line = child.text.trimmingCharacters(in: .whitespacesAndNewlines)
 96                    if line.uppercased().hasPrefix("#+CATEGORY:") {
 97                        keywordCategory = line.dropFirst("#+CATEGORY:".count).trimmingCharacters(in: .whitespaces)
 98                    }
 99                case .block:
100                    if DocumentModel.isSrcBlock(child) {
101                        let lines = child.range
102                        let firstEnd = ns.range(of: "\n", range: NSRange(location: lines.lowerBound, length: lines.count)).location
103                        let lastStart = ns.lineRange(for: NSRange(location: max(lines.lowerBound, lines.upperBound - 1), length: 0)).location
104                        if firstEnd != NSNotFound, firstEnd + 1 <= lastStart { srcBodies.append((firstEnd + 1)..<lastStart) }
105                    }
106                case .planning:
107                    planningLines.append(child.range)
108                case .clock:
109                    break
110                case .nodeProperty:
111                    propertyLines.append(child.range)
112                case .timestamp:
113                    if child.text.hasPrefix("<") { timestampNodes.append(child.offset) }
114                default:
115                    walk(child)
116                }
117            }
118        }
119        walk(tree.root)
120
121        let fileName = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
122        let fileCategory = keywordCategory ?? model.property("CATEGORY", of: nil)?.value ?? fileName
123        let fileTags = model.fileTags
124        let fileArchived = fileTags.contains("ARCHIVE")
125
126        // Archived and commented trees are skipped whole, as `org-agenda-skip` does.
127        var skipped: [Bool] = []
128        var headings: [Heading] = []
129        for (index, info) in model.headings.enumerated() {
130            let own = info.localTags.contains("ARCHIVE") || Self.isCommented(info.title)
131            skipped.append(fileArchived || own || (info.parent.map { skipped[$0] } ?? false))
132            let line = ns.substring(with: NSRange(location: info.headingRange.lowerBound, length: info.headingRange.count))
133            let head = line.replacingOccurrences(of: "^\\*+[ \\t]+", with: "", options: .regularExpression)
134                .trimmingCharacters(in: .newlines)
135
136            var itags: [String] = fileTags
137            for ancestor in model.ancestors(of: index) { itags += model.headings[ancestor].localTags }
138            var tags: [(String, Bool)] = itags.map { ($0, true) } + info.localTags.map { ($0, false) }
139            // `delete-dups` over the reversed list: the most local copy of a tag stays.
140            var seen: Set<String> = []
141            tags = tags.reversed().filter { seen.insert($0.0).inserted }.reversed()
142
143            var category = fileCategory
144            for layer in ([index] + model.ancestors(of: index).reversed()) {
145                if let value = model.headings[layer].properties.last(where: { $0.key.uppercased() == "CATEGORY" && !$0.additive })?.value {
146                    category = value
147                    break
148                }
149            }
150
151            var scheduled: (String, Int)?
152            var deadline: (String, Int)?
153            var planningValues: [String: String] = [:]
154            let afterHeading = info.headingRange.upperBound
155            if let planning = planningLines.first(where: { $0.lowerBound == afterHeading }) {
156                let planningText = ns.substring(with: NSRange(location: planning.lowerBound, length: planning.count))
157                let regex = try! NSRegularExpression(pattern: "\\b(SCHEDULED|DEADLINE): *<([^>]+)>")
158                let pns = planningText as NSString
159                for m in regex.matches(in: planningText, range: NSRange(location: 0, length: pns.length)) {
160                    let value = (pns.substring(with: m.range(at: 2)), planning.lowerBound + m.range(at: 2).location - 1)
161                    if pns.substring(with: m.range(at: 1)) == "SCHEDULED" { scheduled = scheduled ?? value } else { deadline = deadline ?? value }
162                }
163                let any = try! NSRegularExpression(pattern: "\\b(SCHEDULED|DEADLINE|CLOSED): *([\\[<]\(Self.tsInternal)[\\]>])")
164                for m in any.matches(in: planningText, range: NSRange(location: 0, length: pns.length)) {
165                    let key = pns.substring(with: m.range(at: 1))
166                    if planningValues[key] == nil { planningValues[key] = pns.substring(with: m.range(at: 2)) }
167                }
168            }
169            var properties: [String: String] = [:]
170            for property in info.properties {
171                let key = property.key.uppercased()
172                if property.additive, let value = properties[key] {
173                    properties[key] = value + " " + property.value
174                } else {
175                    properties[key] = property.value
176                }
177            }
178            let ownStamps = sectionStamps(index)
179            headings.append(Heading(
180                start: info.headingRange.lowerBound, level: info.level, skipped: skipped[index],
181                title: info.title.trimmingCharacters(in: .whitespaces), priority: info.priority, localTags: info.localTags,
182                properties: properties, planning: planningValues,
183                firstActive: ownStamps.first { $0.hasPrefix("<") }, firstInactive: ownStamps.first { $0.hasPrefix("[") },
184                line: line.trimmingCharacters(in: .newlines), head: head, todo: info.todo, isDone: info.isDone,
185                tags: tags, category: category, scheduled: scheduled, deadline: deadline
186            ))
187        }
188        self.headings = headings
189
190        let starts = model.headings.map(\.headingRange.lowerBound)
191        func heading(at offset: Int) -> Int? {
192            var low = 0
193            var high = starts.count
194            while low < high {
195                let mid = (low + high) / 2
196                if starts[mid] <= offset { low = mid + 1 } else { high = mid }
197            }
198            return low == 0 ? nil : low - 1
199        }
200        func restOfLine(_ offset: Int) -> String {
201            let line = ns.lineRange(for: NSRange(location: offset, length: 0))
202            return ns.substring(with: NSRange(location: offset, length: NSMaxRange(line) - offset)).trimmingCharacters(in: .newlines)
203        }
204
205        // Timestamps: those the parser sees as timestamp objects, and dates in property lines.
206        var stampOffsets = timestampNodes
207        let datePattern = try! NSRegularExpression(pattern: "<[0-9]{4}-[0-9]{2}-[0-9]{2}")
208        for line in propertyLines {
209            for m in datePattern.matches(in: text, range: NSRange(location: line.lowerBound, length: line.count)) {
210                stampOffsets.append(m.range.location)
211            }
212        }
213        var stamps: [Stamp] = []
214        for offset in stampOffsets.sorted() {
215            guard let owner = heading(at: offset), !skipped[owner] else { continue }
216            let rest = restOfLine(offset)
217            guard rest.range(of: "^<[0-9]{4}-[0-9]{2}-[0-9]{2}", options: .regularExpression) != nil else { continue }
218            if Self.inDateRange(offset, ns) { continue }
219            stamps.append(Stamp(offset: offset, heading: owner, rest: rest))
220        }
221        self.stamps = stamps
222
223        // Ranges: org scans the raw text, skipping comment lines, skipped trees and src blocks.
224        var blocks: [Block] = []
225        let range = try! NSRegularExpression(pattern: "<(\(Self.tsInternal))>--?-?<(\(Self.tsInternal))>")
226        for m in range.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
227            let point = NSMaxRange(m.range)
228            let line = ns.substring(with: ns.lineRange(for: NSRange(location: point, length: 0)))
229            if line.range(of: "^\\s*#( |$|\\n)", options: .regularExpression) != nil { continue }
230            guard let owner = heading(at: max(0, point - 1)), !skipped[owner] else { continue }
231            if srcBodies.contains(where: { $0.contains(point) }) { continue }
232            blocks.append(Block(start: ns.substring(with: m.range(at: 1)), end: ns.substring(with: m.range(at: 2)), marker: point, heading: owner))
233        }
234        self.blocks = blocks
235    }
236
237    /// `org-ts--internal-regexp`.
238    static let tsInternal = "[0-9]{4}-[0-9]{2}-[0-9]{2}(?: .*?)?"
239
240    /// `org-element` reads a title starting with `COMMENT` as a commented heading.
241    static func isCommented(_ title: String) -> Bool {
242        title == "COMMENT" || title.hasPrefix("COMMENT ")
243    }
244
245    /// `org-at-date-range-p` with point just after the date that starts at `offset`.
246    static func inDateRange(_ offset: Int, _ ns: NSString) -> Bool {
247        let point = offset + 11
248        let line = ns.lineRange(for: NSRange(location: offset, length: 0))
249        let regex = try! NSRegularExpression(pattern: "[\\[<](\(tsInternal))[\\]>]--?-?[\\[<](\(tsInternal))[\\]>]")
250        for m in regex.matches(in: ns as String, range: line) {
251            if m.range.location > point { break }
252            if NSMaxRange(m.range) >= point { return true }
253        }
254        return false
255    }
256}