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