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