Sources/OrgCore/Agenda/AgendaSource.swift
328 lines · 17135 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 /// `STYLE: habit`.
39 let isHabit: Bool
40 /// `org-habit-parse-todo`, nil where it signals an error.
41 let habit: Habit?
42 }
43
44 struct Stamp: Sendable {
45 let offset: Int
46 let heading: Int
47 /// From the `<` to the end of the line.
48 let rest: String
49 }
50
51 struct Block: Sendable {
52 let start: String
53 let end: String
54 /// End of the range; org's marker sits there.
55 let marker: Int
56 let heading: Int
57 }
58
59 /// A `CLOSED:`, `CLOCK:` or `- State "…"` line, for log mode (`org-agenda-get-progress`).
60 struct Progress: Sendable {
61 enum Kind: Sendable { case closed, clock, state }
62 let kind: Kind
63 let offset: Int
64 let heading: Int
65 /// `YYYY-MM-DD` of the first timestamp.
66 let date: String
67 /// The timestamp, from the keyword; a clock's ends with its end time (`[… 10:00-11:30]`).
68 let timestamp: String
69 /// A clock's duration, or `-`.
70 let clocked: String
71 /// The state a note records.
72 let state: String?
73 /// The first line of the note under it.
74 let note: String?
75 }
76
77 let headings: [Heading]
78 let stamps: [Stamp]
79 let blocks: [Block]
80 let progress: [Progress]
81 /// The file's TODO keywords, active and done.
82 let keywords: [String]
83 let priorities: Priorities
84
85 public init(path: String, text: String, defaults: OrgSettings = .default) {
86 self.path = path
87 let tree = OrgParser.parse(text, defaults: defaults)
88 let model = DocumentModel(tree: tree)
89 let ns = text as NSString
90 let settings = tree.settings
91 keywords = settings.todoSequences.flatMap { $0.active.map(\.name) + $0.done.map(\.name) }
92 priorities = settings.priorities
93
94 var stampsByHeading: [Int: [String]] = [:]
95 var headingIndex = -1
96 func collect(_ node: SyntaxNode) {
97 for child in node.children {
98 if child.kind == .heading { headingIndex += 1 }
99 if child.kind == .timestamp, headingIndex >= 0 {
100 stampsByHeading[headingIndex, default: []].append(child.text)
101 } else if child.kind != .block, child.kind != .planning {
102 collect(child)
103 }
104 }
105 }
106 collect(tree.root)
107 func sectionStamps(_ index: Int) -> [String] { stampsByHeading[index] ?? [] }
108
109 var keywordCategory: String?
110 var srcBodies: [Range<Int>] = []
111 var planningLines: [Range<Int>] = []
112 var timestampNodes: [Int] = []
113 var propertyLines: [Range<Int>] = []
114 func walk(_ node: SyntaxNode) {
115 for child in node.children {
116 switch child.kind {
117 case .keyword:
118 let line = child.text.trimmingCharacters(in: .whitespacesAndNewlines)
119 if line.uppercased().hasPrefix("#+CATEGORY:") {
120 keywordCategory = line.dropFirst("#+CATEGORY:".count).trimmingCharacters(in: .whitespaces)
121 }
122 case .block:
123 if DocumentModel.isSrcBlock(child) {
124 let lines = child.range
125 let firstEnd = ns.range(of: "\n", range: NSRange(location: lines.lowerBound, length: lines.count)).location
126 let lastStart = ns.lineRange(for: NSRange(location: max(lines.lowerBound, lines.upperBound - 1), length: 0)).location
127 if firstEnd != NSNotFound, firstEnd + 1 <= lastStart { srcBodies.append((firstEnd + 1)..<lastStart) }
128 }
129 case .planning:
130 planningLines.append(child.range)
131 case .clock:
132 break
133 case .nodeProperty:
134 propertyLines.append(child.range)
135 case .timestamp:
136 if child.text.hasPrefix("<") { timestampNodes.append(child.offset) }
137 default:
138 walk(child)
139 }
140 }
141 }
142 walk(tree.root)
143
144 let fileName = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
145 let fileCategory = keywordCategory ?? model.property("CATEGORY", of: nil)?.value ?? fileName
146 let fileTags = model.fileTags
147 let fileArchived = fileTags.contains("ARCHIVE")
148
149 // Archived and commented trees are skipped whole, as `org-agenda-skip` does.
150 var skipped: [Bool] = []
151 var headings: [Heading] = []
152 for (index, info) in model.headings.enumerated() {
153 let own = info.localTags.contains("ARCHIVE") || Self.isCommented(info.title)
154 skipped.append(fileArchived || own || (info.parent.map { skipped[$0] } ?? false))
155 let line = ns.substring(with: NSRange(location: info.headingRange.lowerBound, length: info.headingRange.count))
156 let head = line.replacingOccurrences(of: "^\\*+[ \\t]+", with: "", options: .regularExpression)
157 .trimmingCharacters(in: .newlines)
158
159 var itags: [String] = fileTags
160 for ancestor in model.ancestors(of: index) { itags += model.headings[ancestor].localTags }
161 var tags: [(String, Bool)] = itags.map { ($0, true) } + info.localTags.map { ($0, false) }
162 // `delete-dups` over the reversed list: the most local copy of a tag stays.
163 var seen: Set<String> = []
164 tags = tags.reversed().filter { seen.insert($0.0).inserted }.reversed()
165
166 var category = fileCategory
167 for layer in ([index] + model.ancestors(of: index).reversed()) {
168 if let value = model.headings[layer].properties.last(where: { $0.key.uppercased() == "CATEGORY" && !$0.additive })?.value {
169 category = value
170 break
171 }
172 }
173
174 var scheduled: (String, Int)?
175 var deadline: (String, Int)?
176 var planningValues: [String: String] = [:]
177 let afterHeading = info.headingRange.upperBound
178 if let planning = planningLines.first(where: { $0.lowerBound == afterHeading }) {
179 let planningText = ns.substring(with: NSRange(location: planning.lowerBound, length: planning.count))
180 let regex = try! NSRegularExpression(pattern: "\\b(SCHEDULED|DEADLINE): *<([^>]+)>")
181 let pns = planningText as NSString
182 for m in regex.matches(in: planningText, range: NSRange(location: 0, length: pns.length)) {
183 let value = (pns.substring(with: m.range(at: 2)), planning.lowerBound + m.range(at: 2).location - 1)
184 if pns.substring(with: m.range(at: 1)) == "SCHEDULED" { scheduled = scheduled ?? value } else { deadline = deadline ?? value }
185 }
186 let any = try! NSRegularExpression(pattern: "\\b(SCHEDULED|DEADLINE|CLOSED): *([\\[<]\(Self.tsInternal)[\\]>])")
187 for m in any.matches(in: planningText, range: NSRange(location: 0, length: pns.length)) {
188 let key = pns.substring(with: m.range(at: 1))
189 if planningValues[key] == nil { planningValues[key] = pns.substring(with: m.range(at: 2)) }
190 }
191 }
192 var properties: [String: String] = [:]
193 for property in info.properties {
194 let key = property.key.uppercased()
195 if property.additive, let value = properties[key] {
196 properties[key] = value + " " + property.value
197 } else {
198 properties[key] = property.value
199 }
200 }
201 let ownStamps = sectionStamps(index)
202 let isHabit = properties["STYLE"]?.trimmingCharacters(in: .whitespaces) == "habit"
203 var habit: Habit?
204 if isHabit, let scheduled {
205 let end = index + 1 < model.headings.count ? model.headings[index + 1].headingRange.lowerBound : ns.length
206 let entry = ns.substring(with: NSRange(location: info.headingRange.lowerBound, length: end - info.headingRange.lowerBound))
207 habit = Habit.parse(entry: entry, scheduled: scheduled.0, doneKeywords: settings.todoSequences.flatMap { $0.done.map(\.name) })
208 }
209 headings.append(Heading(
210 start: info.headingRange.lowerBound, level: info.level, skipped: skipped[index],
211 title: info.title.trimmingCharacters(in: .whitespaces), priority: info.priority, localTags: info.localTags,
212 properties: properties, planning: planningValues,
213 firstActive: ownStamps.first { $0.hasPrefix("<") }, firstInactive: ownStamps.first { $0.hasPrefix("[") },
214 line: line.trimmingCharacters(in: .newlines), head: head, todo: info.todo, isDone: info.isDone,
215 tags: tags, category: category, scheduled: scheduled, deadline: deadline, isHabit: isHabit, habit: habit
216 ))
217 }
218 self.headings = headings
219
220 let starts = model.headings.map(\.headingRange.lowerBound)
221 func heading(at offset: Int) -> Int? {
222 var low = 0
223 var high = starts.count
224 while low < high {
225 let mid = (low + high) / 2
226 if starts[mid] <= offset { low = mid + 1 } else { high = mid }
227 }
228 return low == 0 ? nil : low - 1
229 }
230 func restOfLine(_ offset: Int) -> String {
231 let line = ns.lineRange(for: NSRange(location: offset, length: 0))
232 return ns.substring(with: NSRange(location: offset, length: NSMaxRange(line) - offset)).trimmingCharacters(in: .newlines)
233 }
234
235 // Timestamps: those the parser sees as timestamp objects, and dates in property lines.
236 var stampOffsets = timestampNodes
237 let datePattern = try! NSRegularExpression(pattern: "<[0-9]{4}-[0-9]{2}-[0-9]{2}")
238 for line in propertyLines {
239 for m in datePattern.matches(in: text, range: NSRange(location: line.lowerBound, length: line.count)) {
240 stampOffsets.append(m.range.location)
241 }
242 }
243 var stamps: [Stamp] = []
244 for offset in stampOffsets.sorted() {
245 guard let owner = heading(at: offset), !skipped[owner] else { continue }
246 let rest = restOfLine(offset)
247 guard rest.range(of: "^<[0-9]{4}-[0-9]{2}-[0-9]{2}", options: .regularExpression) != nil else { continue }
248 if Self.inDateRange(offset, ns) { continue }
249 stamps.append(Stamp(offset: offset, heading: owner, rest: rest))
250 }
251 self.stamps = stamps
252
253 // Ranges: org scans the raw text, skipping comment lines, skipped trees and src blocks.
254 var blocks: [Block] = []
255 let range = try! NSRegularExpression(pattern: "<(\(Self.tsInternal))>--?-?<(\(Self.tsInternal))>")
256 for m in range.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
257 let point = NSMaxRange(m.range)
258 let line = ns.substring(with: ns.lineRange(for: NSRange(location: point, length: 0)))
259 if line.range(of: "^\\s*#( |$|\\n)", options: .regularExpression) != nil { continue }
260 guard let owner = heading(at: max(0, point - 1)), !skipped[owner] else { continue }
261 if srcBodies.contains(where: { $0.contains(point) }) { continue }
262 blocks.append(Block(start: ns.substring(with: m.range(at: 1)), end: ns.substring(with: m.range(at: 2)), marker: point, heading: owner))
263 }
264 self.blocks = blocks
265
266 // Log lines: org searches the raw text, then the heading above each match.
267 let keywordPattern = keywords.map(NSRegularExpression.escapedPattern(for:)).joined(separator: "|")
268 let logLine = try! NSRegularExpression(pattern: "(\\bCLOSED:|\\bCLOCK:|- +State \"(\(keywordPattern.isEmpty ? "(?!)" : keywordPattern))\".*?) *\\[([0-9]{4}-[0-9]{2}-[0-9]{2})")
269 let inactive = try! NSRegularExpression(pattern: "\\[([0-9]{4}-[0-9]{2}-[0-9]{2}( +[^\\]+0-9>\\r\\n -]+)?( +([0-9]{1,2}):([0-9]{2}))?)\\]")
270 let clockEnd = try! NSRegularExpression(pattern: "([0-9]{1,2}:[0-9]{2})\\].*?([0-9]{1,2}:[0-9]{2})")
271 let stateNote = try! NSRegularExpression(pattern: ".*\\\\\\n[ \\t]*([^-\\n \\t].*?)[ \\t]*$", options: .anchorsMatchLines)
272 let clockNote = try! NSRegularExpression(pattern: ".*\\n[ \\t]*-[ \\t]+([^-\\n \\t].*?)[ \\t]*$", options: .anchorsMatchLines)
273 var progress: [Progress] = []
274 for m in logLine.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
275 guard let owner = heading(at: m.range.location), !skipped[owner] else { continue }
276 let keyword = ns.substring(with: m.range(at: 1))
277 let kind: Progress.Kind = keyword == "CLOSED:" ? .closed : keyword == "CLOCK:" ? .clock : .state
278 var timestamp = restOfLine(m.range.location)
279 var clocked = "-"
280 let tns = timestamp as NSString
281 if let ts = inactive.firstMatch(in: timestamp, range: NSRange(location: 0, length: tns.length)) {
282 let rest = tns.substring(from: NSMaxRange(ts.range))
283 timestamp = tns.substring(to: NSMaxRange(ts.range))
284 let rns = rest as NSString
285 if kind == .clock, let end = clockEnd.firstMatch(in: rest, range: NSRange(location: 0, length: rns.length)) {
286 timestamp = String(timestamp.dropLast()) + "-" + rns.substring(with: end.range(at: 1)) + "]"
287 clocked = rns.substring(with: end.range(at: 2))
288 }
289 }
290 // The note: after a state line ending in `\\`, or a list item under a clock line.
291 var note: String?
292 let after = NSMaxRange(m.range)
293 let notePattern: NSRegularExpression? = switch kind {
294 case .state: stateNote
295 case .clock: clockNote
296 case .closed: nil
297 }
298 if let notePattern, let n = notePattern.firstMatch(in: text, options: .anchored, range: NSRange(location: after, length: ns.length - after)) {
299 note = ns.substring(with: n.range(at: 1))
300 }
301 progress.append(Progress(
302 kind: kind, offset: m.range.location, heading: owner, date: ns.substring(with: m.range(at: 3)), timestamp: timestamp,
303 clocked: clocked, state: m.range(at: 2).location == NSNotFound ? nil : ns.substring(with: m.range(at: 2)), note: note
304 ))
305 }
306 self.progress = progress
307 }
308
309 /// `org-ts--internal-regexp`.
310 static let tsInternal = "[0-9]{4}-[0-9]{2}-[0-9]{2}(?: .*?)?"
311
312 /// `org-element` reads a title starting with `COMMENT` as a commented heading.
313 static func isCommented(_ title: String) -> Bool {
314 title == "COMMENT" || title.hasPrefix("COMMENT ")
315 }
316
317 /// `org-at-date-range-p` with point just after the date that starts at `offset`.
318 static func inDateRange(_ offset: Int, _ ns: NSString) -> Bool {
319 let point = offset + 11
320 let line = ns.lineRange(for: NSRange(location: offset, length: 0))
321 let regex = try! NSRegularExpression(pattern: "[\\[<](\(tsInternal))[\\]>]--?-?[\\[<](\(tsInternal))[\\]>]")
322 for m in regex.matches(in: ns as String, range: line) {
323 if m.range.location > point { break }
324 if NSMaxRange(m.range) >= point { return true }
325 }
326 return false
327 }
328}