Sources/OrgCore/Agenda/AgendaSource.swift
396 lines · 20946 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 static let planningRegex = try! NSRegularExpression(pattern: "\\b(SCHEDULED|DEADLINE): *<([^>]+)>")
7 static let planningAnyRegex = try! NSRegularExpression(pattern: "\\b(SCHEDULED|DEADLINE|CLOSED): *([\\[<]\(Self.tsInternal)[\\]>])")
8 static let activeRangeRegex = try! NSRegularExpression(pattern: "<(\(Self.tsInternal))>--?-?<(\(Self.tsInternal))>")
9 static let inactiveRegex = try! NSRegularExpression(pattern: "\\[([0-9]{4}-[0-9]{2}-[0-9]{2}( +[^\\]+0-9>\\r\\n -]+)?( +([0-9]{1,2}):([0-9]{2}))?)\\]")
10 static let dateRangeRegex = try! NSRegularExpression(pattern: "[\\[<](\(tsInternal))[\\]>]--?-?[\\[<](\(tsInternal))[\\]>]")
11
12 public let path: String
13 /// The file names `#+SETUPFILE`s.
14 public let readsSetupFiles: Bool
15
16 struct Heading: Sendable {
17 /// Start of the heading line.
18 let start: Int
19 let level: Int
20 /// In an archived or commented tree, which the agenda skips.
21 let skipped: Bool
22 /// The title without keyword, priority and tags (`ITEM`).
23 let title: String
24 /// The priority cookie's value.
25 let priority: String?
26 let localTags: [String]
27 /// Upper-cased keys of the entry's own drawer.
28 let properties: [String: String]
29 /// Planning timestamps with brackets, for property matches.
30 let planning: [String: String]
31 /// The first active and inactive timestamps in the entry (`TIMESTAMP`, `TIMESTAMP_IA`).
32 let firstActive: String?
33 let firstInactive: String?
34 /// The heading line without its newline.
35 let line: String
36 /// The line after the stars.
37 let head: String
38 let todo: String?
39 let isDone: Bool
40 /// Inherited tags first; the flag marks inherited ones.
41 let tags: [(name: String, inherited: Bool)]
42 let category: String
43 /// The planning timestamp without brackets, and the position of its `<`.
44 let scheduled: (raw: String, offset: Int)?
45 let deadline: (raw: String, offset: Int)?
46 /// `STYLE: habit`.
47 let isHabit: Bool
48 /// `org-habit-parse-todo`, nil where it signals an error.
49 let habit: Habit?
50 /// `org-entry-blocked-p` with only `org-enforce-todo-checkbox-dependencies`, and with
51 /// only `org-enforce-todo-dependencies`.
52 let blockedByCheckboxes: Bool
53 let blockedByHierarchy: Bool
54 }
55
56 struct Stamp: Sendable {
57 let offset: Int
58 let heading: Int
59 /// From the `<` to the end of the line.
60 let rest: String
61 }
62
63 struct Block: Sendable {
64 let start: String
65 let end: String
66 /// End of the range; org's marker sits there.
67 let marker: Int
68 let heading: Int
69 }
70
71 /// A `CLOSED:`, `CLOCK:` or `- State "…"` line, for log mode (`org-agenda-get-progress`).
72 struct Progress: Sendable {
73 enum Kind: Sendable { case closed, clock, state }
74 let kind: Kind
75 let offset: Int
76 let heading: Int
77 /// `YYYY-MM-DD` of the first timestamp.
78 let date: String
79 /// The timestamp, from the keyword; a clock's ends with its end time (`[… 10:00-11:30]`).
80 let timestamp: String
81 /// A clock's duration, or `-`.
82 let clocked: String
83 /// The state a note records.
84 let state: String?
85 /// The first line of the note under it.
86 let note: String?
87 }
88
89 /// A `%%(…)` line (`org-agenda-get-sexps`).
90 struct SexpLine: Sendable {
91 /// Start of the line.
92 let offset: Int
93 /// The heading the line is under.
94 let heading: Int
95 let sexp: Sexp
96 /// The rest of the line after the sexp.
97 let entry: String
98 }
99
100 let headings: [Heading]
101 let stamps: [Stamp]
102 let sexps: [SexpLine]
103 let blocks: [Block]
104 let progress: [Progress]
105 /// The file's TODO keywords, active and done.
106 let keywords: [String]
107 /// The active ones (`org-not-done-keywords`).
108 let notDoneKeywords: [String]
109 /// Each keyword's first done keyword in the first sequence that has it.
110 let firstDone: [String: String]
111 /// The file's text, for the search view.
112 public let text: String
113 let priorities: Priorities
114
115 /// `checksBlocking` false leaves every heading unblocked, for when neither enforce
116 /// setting is on.
117 public init(path: String, text: String, defaults: OrgSettings = .default, checksBlocking: Bool = true) {
118 self.path = path
119 readsSetupFiles = text.containsIgnoringASCIICase("#+setupfile:")
120 let tree = OrgParser.parse(text, defaults: defaults)
121 let model = DocumentModel(tree: tree)
122 let ns = text as NSString
123 let settings = tree.settings
124 keywords = settings.todoSequences.flatMap { $0.active.map(\.name) + $0.done.map(\.name) }
125 notDoneKeywords = settings.todoSequences.flatMap { $0.active.map(\.name) }
126 var firstDone: [String: String] = [:]
127 for sequence in settings.todoSequences {
128 guard let done = sequence.done.first?.name else { continue }
129 for keyword in sequence.active + sequence.done where firstDone[keyword.name] == nil { firstDone[keyword.name] = done }
130 }
131 self.firstDone = firstDone
132 self.text = text
133 priorities = settings.priorities
134
135 var stampsByHeading: [Int: [String]] = [:]
136 var headingIndex = -1
137 func collect(_ node: SyntaxNode) {
138 for child in node.children {
139 if child.kind == .heading { headingIndex += 1 }
140 if child.kind == .timestamp, headingIndex >= 0 {
141 stampsByHeading[headingIndex, default: []].append(child.text)
142 } else if child.kind != .block, child.kind != .planning {
143 collect(child)
144 }
145 }
146 }
147 collect(tree.root)
148 func sectionStamps(_ index: Int) -> [String] { stampsByHeading[index] ?? [] }
149
150 var keywordCategory = SetupFile.keywords(tree.settings.setupKeywords).last { $0.key == "CATEGORY" }?.value.trimmingCharacters(in: .whitespaces)
151 var srcBodies: [Range<Int>] = []
152 var planningLines: [Range<Int>] = []
153 var timestampNodes: [Int] = []
154 var propertyLines: [Range<Int>] = []
155 func walk(_ node: SyntaxNode) {
156 for child in node.children {
157 switch child.kind {
158 case .keyword:
159 let line = child.text.trimmingCharacters(in: .whitespacesAndNewlines)
160 if line.uppercased().hasPrefix("#+CATEGORY:") {
161 keywordCategory = line.dropFirst("#+CATEGORY:".count).trimmingCharacters(in: .whitespaces)
162 }
163 case .block:
164 if DocumentModel.isSrcBlock(child) {
165 let lines = child.range
166 let firstEnd = ns.range(of: "\n", range: NSRange(location: lines.lowerBound, length: lines.count)).location
167 let lastStart = ns.lineRange(for: NSRange(location: max(lines.lowerBound, lines.upperBound - 1), length: 0)).location
168 if firstEnd != NSNotFound, firstEnd + 1 <= lastStart { srcBodies.append((firstEnd + 1)..<lastStart) }
169 }
170 case .planning:
171 planningLines.append(child.range)
172 case .clock:
173 break
174 case .nodeProperty:
175 propertyLines.append(child.range)
176 case .timestamp:
177 if child.text.hasPrefix("<") { timestampNodes.append(child.offset) }
178 default:
179 walk(child)
180 }
181 }
182 }
183 walk(tree.root)
184
185 let fileName = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
186 let fileCategory = keywordCategory ?? model.property("CATEGORY", of: nil)?.value ?? fileName
187 let fileTags = model.fileTags
188 let fileArchived = fileTags.contains("ARCHIVE")
189
190 // Archived and commented trees are skipped whole, as `org-agenda-skip` does.
191 var skipped: [Bool] = []
192 var headings: [Heading] = []
193 var options = EditingOptions.org
194 options.listAllowAlphabetical = settings.listAllowAlphabetical
195 let buffer = EmacsBuffer(text, point: 0, settings: settings, options: options)
196 for (index, info) in model.headings.enumerated() {
197 let own = info.localTags.contains("ARCHIVE") || Self.isCommented(info.title)
198 skipped.append(fileArchived || own || (info.parent.map { skipped[$0] } ?? false))
199 let line = ns.substring(with: NSRange(location: info.headingRange.lowerBound, length: info.headingRange.count))
200 let head = line.replacingOccurrences(of: "^\\*+[ \\t]+", with: "", options: .regularExpression)
201 .trimmingCharacters(in: .newlines)
202
203 var itags: [String] = fileTags
204 for ancestor in model.ancestors(of: index) { itags += model.headings[ancestor].localTags }
205 var tags: [(String, Bool)] = itags.map { ($0, true) } + info.localTags.map { ($0, false) }
206 // `delete-dups` over the reversed list: the most local copy of a tag stays.
207 var seen: Set<String> = []
208 tags = tags.reversed().filter { seen.insert($0.0).inserted }.reversed()
209
210 var category = fileCategory
211 for layer in ([index] + model.ancestors(of: index).reversed()) {
212 if let value = model.headings[layer].properties.last(where: { $0.key.uppercased() == "CATEGORY" && !$0.additive })?.value {
213 category = value
214 break
215 }
216 }
217
218 var scheduled: (String, Int)?
219 var deadline: (String, Int)?
220 var planningValues: [String: String] = [:]
221 let afterHeading = info.headingRange.upperBound
222 if let planning = planningLines.first(where: { $0.lowerBound == afterHeading }) {
223 let planningText = ns.substring(with: NSRange(location: planning.lowerBound, length: planning.count))
224 let regex = Self.planningRegex
225 let pns = planningText as NSString
226 for m in regex.matches(in: planningText, range: NSRange(location: 0, length: pns.length)) {
227 let value = (pns.substring(with: m.range(at: 2)), planning.lowerBound + m.range(at: 2).location - 1)
228 if pns.substring(with: m.range(at: 1)) == "SCHEDULED" { scheduled = scheduled ?? value } else { deadline = deadline ?? value }
229 }
230 let any = Self.planningAnyRegex
231 for m in any.matches(in: planningText, range: NSRange(location: 0, length: pns.length)) {
232 let key = pns.substring(with: m.range(at: 1))
233 if planningValues[key] == nil { planningValues[key] = pns.substring(with: m.range(at: 2)) }
234 }
235 }
236 var properties: [String: String] = [:]
237 for property in info.properties {
238 let key = property.key.uppercased()
239 if property.additive, let value = properties[key] {
240 properties[key] = value + " " + property.value
241 } else {
242 properties[key] = property.value
243 }
244 }
245 let ownStamps = sectionStamps(index)
246 let isHabit = properties["STYLE"]?.trimmingCharacters(in: .whitespaces) == "habit"
247 var habit: Habit?
248 if isHabit, let scheduled {
249 let end = index + 1 < model.headings.count ? model.headings[index + 1].headingRange.lowerBound : ns.length
250 let entry = ns.substring(with: NSRange(location: info.headingRange.lowerBound, length: end - info.headingRange.lowerBound))
251 habit = Habit.parse(entry: entry, scheduled: scheduled.0, doneKeywords: settings.todoSequences.flatMap { $0.done.map(\.name) })
252 }
253 var blockedByCheckboxes = false
254 var blockedByHierarchy = false
255 if checksBlocking, info.todo != nil, !info.isDone, buffer.localProperty("NOBLOCKING", heading: info.headingRange.lowerBound).map({ $0 == "nil" }) ?? true {
256 buffer.point = info.headingRange.lowerBound
257 blockedByCheckboxes = buffer.hasOpenCheckbox()
258 blockedByHierarchy = buffer.hierarchyBlocker() != nil
259 }
260 headings.append(Heading(
261 start: info.headingRange.lowerBound, level: info.level, skipped: skipped[index],
262 title: info.title.trimmingCharacters(in: .whitespaces), priority: info.priority, localTags: info.localTags,
263 properties: properties, planning: planningValues,
264 firstActive: ownStamps.first { $0.hasPrefix("<") }, firstInactive: ownStamps.first { $0.hasPrefix("[") },
265 line: line.trimmingCharacters(in: .newlines), head: head, todo: info.todo, isDone: info.isDone,
266 tags: tags, category: category, scheduled: scheduled, deadline: deadline, isHabit: isHabit, habit: habit,
267 blockedByCheckboxes: blockedByCheckboxes, blockedByHierarchy: blockedByHierarchy
268 ))
269 }
270 self.headings = headings
271
272 let starts = model.headings.map(\.headingRange.lowerBound)
273 func heading(at offset: Int) -> Int? {
274 var low = 0
275 var high = starts.count
276 while low < high {
277 let mid = (low + high) / 2
278 if starts[mid] <= offset { low = mid + 1 } else { high = mid }
279 }
280 return low == 0 ? nil : low - 1
281 }
282 func restOfLine(_ offset: Int) -> String {
283 let line = ns.lineRange(for: NSRange(location: offset, length: 0))
284 return ns.substring(with: NSRange(location: offset, length: NSMaxRange(line) - offset)).trimmingCharacters(in: .newlines)
285 }
286
287 // Timestamps: those the parser sees as timestamp objects, and dates in property lines.
288 var stampOffsets = timestampNodes
289 let datePattern = try! NSRegularExpression(pattern: "<[0-9]{4}-[0-9]{2}-[0-9]{2}")
290 for line in propertyLines {
291 for m in datePattern.matches(in: text, range: NSRange(location: line.lowerBound, length: line.count)) {
292 stampOffsets.append(m.range.location)
293 }
294 }
295 var stamps: [Stamp] = []
296 for offset in stampOffsets.sorted() {
297 guard let owner = heading(at: offset), !skipped[owner] else { continue }
298 let rest = restOfLine(offset)
299 guard rest.range(of: "^<([0-9]{4}-[0-9]{2}-[0-9]{2}|%%\\()", options: .regularExpression) != nil else { continue }
300 if Self.inDateRange(offset, ns) { continue }
301 stamps.append(Stamp(offset: offset, heading: owner, rest: rest))
302 }
303 self.stamps = stamps
304
305 // Sexp lines: org searches the raw text for `%%(` at the start of a line. Before the
306 // first heading org's agenda signals an error; they're left out.
307 var sexps: [SexpLine] = []
308 let sexpLine = try! NSRegularExpression(pattern: "^&?%%\\(", options: .anchorsMatchLines)
309 for m in sexpLine.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
310 guard let owner = heading(at: m.range.location), !skipped[owner] else { continue }
311 let open = NSMaxRange(m.range) - 1
312 let tail = ns.substring(with: NSRange(location: open, length: min(ns.length - open, 4096)))
313 guard let (sexp, length) = try? LispReader.readFirst(tail) else { continue }
314 let afterSexp = String(tail.dropFirst(length))
315 let lineRest = afterSexp.prefix { $0 != "\n" && $0 != "\r" }
316 let entry = lineRest.trimmingCharacters(in: CharacterSet(charactersIn: " \t"))
317 sexps.append(SexpLine(offset: m.range.location, heading: owner, sexp: sexp, entry: entry))
318 }
319 self.sexps = sexps
320
321 // Ranges: org scans the raw text, skipping comment lines, skipped trees and src blocks.
322 var blocks: [Block] = []
323 let range = Self.activeRangeRegex
324 for m in range.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
325 let point = NSMaxRange(m.range)
326 let line = ns.substring(with: ns.lineRange(for: NSRange(location: point, length: 0)))
327 if line.range(of: "^\\s*#( |$|\\n)", options: .regularExpression) != nil { continue }
328 guard let owner = heading(at: max(0, point - 1)), !skipped[owner] else { continue }
329 if srcBodies.contains(where: { $0.contains(point) }) { continue }
330 blocks.append(Block(start: ns.substring(with: m.range(at: 1)), end: ns.substring(with: m.range(at: 2)), marker: point, heading: owner))
331 }
332 self.blocks = blocks
333
334 // Log lines: org searches the raw text, then the heading above each match.
335 let keywordPattern = keywords.map(NSRegularExpression.escapedPattern(for:)).joined(separator: "|")
336 let logLine = try! NSRegularExpression(pattern: "(\\bCLOSED:|\\bCLOCK:|- +State \"(\(keywordPattern.isEmpty ? "(?!)" : keywordPattern))\".*?) *\\[([0-9]{4}-[0-9]{2}-[0-9]{2})")
337 let inactive = Self.inactiveRegex
338 let clockEnd = try! NSRegularExpression(pattern: "([0-9]{1,2}:[0-9]{2})\\].*?([0-9]{1,2}:[0-9]{2})")
339 let stateNote = try! NSRegularExpression(pattern: ".*\\\\\\n[ \\t]*([^-\\n \\t].*?)[ \\t]*$", options: .anchorsMatchLines)
340 let clockNote = try! NSRegularExpression(pattern: ".*\\n[ \\t]*-[ \\t]+([^-\\n \\t].*?)[ \\t]*$", options: .anchorsMatchLines)
341 var progress: [Progress] = []
342 for m in logLine.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
343 guard let owner = heading(at: m.range.location), !skipped[owner] else { continue }
344 let keyword = ns.substring(with: m.range(at: 1))
345 let kind: Progress.Kind = keyword == "CLOSED:" ? .closed : keyword == "CLOCK:" ? .clock : .state
346 var timestamp = restOfLine(m.range.location)
347 var clocked = "-"
348 let tns = timestamp as NSString
349 if let ts = inactive.firstMatch(in: timestamp, range: NSRange(location: 0, length: tns.length)) {
350 let rest = tns.substring(from: NSMaxRange(ts.range))
351 timestamp = tns.substring(to: NSMaxRange(ts.range))
352 let rns = rest as NSString
353 if kind == .clock, let end = clockEnd.firstMatch(in: rest, range: NSRange(location: 0, length: rns.length)) {
354 timestamp = String(timestamp.dropLast()) + "-" + rns.substring(with: end.range(at: 1)) + "]"
355 clocked = rns.substring(with: end.range(at: 2))
356 }
357 }
358 // The note: after a state line ending in `\\`, or a list item under a clock line.
359 var note: String?
360 let after = NSMaxRange(m.range)
361 let notePattern: NSRegularExpression? = switch kind {
362 case .state: stateNote
363 case .clock: clockNote
364 case .closed: nil
365 }
366 if let notePattern, let n = notePattern.firstMatch(in: text, options: .anchored, range: NSRange(location: after, length: ns.length - after)) {
367 note = ns.substring(with: n.range(at: 1))
368 }
369 progress.append(Progress(
370 kind: kind, offset: m.range.location, heading: owner, date: ns.substring(with: m.range(at: 3)), timestamp: timestamp,
371 clocked: clocked, state: m.range(at: 2).location == NSNotFound ? nil : ns.substring(with: m.range(at: 2)), note: note
372 ))
373 }
374 self.progress = progress
375 }
376
377 /// `org-ts--internal-regexp`.
378 static let tsInternal = "[0-9]{4}-[0-9]{2}-[0-9]{2}(?: .*?)?"
379
380 /// `org-element` reads a title starting with `COMMENT` as a commented heading.
381 static func isCommented(_ title: String) -> Bool {
382 title == "COMMENT" || title.hasPrefix("COMMENT ")
383 }
384
385 /// `org-at-date-range-p` with point just after the date that starts at `offset`.
386 static func inDateRange(_ offset: Int, _ ns: NSString) -> Bool {
387 let point = offset + 11
388 let line = ns.lineRange(for: NSRange(location: offset, length: 0))
389 let regex = Self.dateRangeRegex
390 for m in regex.matches(in: ns as String, range: line) {
391 if m.range.location > point { break }
392 if NSMaxRange(m.range) >= point { return true }
393 }
394 return false
395 }
396}