Sources/OrgCore/Agenda/Agenda.swift
428 lines · 21480 bytes
1import Foundation
2
3public struct AgendaItem: Sendable, Equatable {
4 public enum Kind: String, Sendable {
5 case deadline
6 case upcomingDeadline = "upcoming-deadline"
7 case scheduled
8 case pastScheduled = "past-scheduled"
9 case timestamp
10 case block
11 case timeGrid
12 case currentTime
13 case todo
14 case tagsMatch = "tagsmatch"
15 }
16
17 public let kind: Kind
18 public let path: String?
19 /// Start of the entry's heading line.
20 public let headingOffset: Int?
21 /// The heading line as it was read, from its stars, to check the offsets still hold.
22 public let headingLine: String?
23 /// Where org's marker points: the timestamp, or the end of a range.
24 public let markerOffset: Int?
25 public let category: String
26 /// `HHMM`, when the item has a time of day.
27 public let timeOfDay: Int?
28 /// `14:00-15:00`, ` 9:00......`, or empty.
29 public let time: String
30 /// The leader: `Deadline: `, `Sched. 2x: `, `(1/3): `.
31 public let extra: String
32 /// The heading text as shown: TODO keyword, priority, title, without tags.
33 public let text: String
34 public let tags: [String]
35 public let todo: String?
36 public let isDone: Bool
37 public let urgency: Int
38 /// The line as org prints it, with one space before the tags.
39 public let line: String
40}
41
42public struct AgendaDay: Sendable, Equatable {
43 /// Emacs's absolute day number (`Days`).
44 public let day: Int
45 public let isToday: Bool
46 /// `Monday 5 October 2026 W41`.
47 public let header: String
48 public let items: [AgendaItem]
49}
50
51public struct AgendaOptions: Sendable, Equatable {
52 public var deadlineWarningDays = 14
53 public var gridTimes = [800, 1000, 1200, 1400, 1600, 1800, 2000]
54 public var gridTrailing = " ┄┄┄┄┄ "
55 public var gridLine = "┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄"
56 public var currentTimeLine = "← now ───────────────────────────────────────────────"
57
58 public init() {}
59
60 /// What Emacs shows without a graphical display.
61 public static let terminal: AgendaOptions = {
62 var options = AgendaOptions()
63 options.gridTrailing = "......"
64 options.gridLine = "----------------"
65 options.currentTimeLine = "now - - - - - - - - - - - - - - - - - - - - - - - - -"
66 return options
67 }()
68}
69
70/// `org-agenda-list`.
71public enum Agenda {
72 public static func list(
73 _ sources: [AgendaSource], start: Int, days: Int, today: Int, now: (hour: Int, minute: Int),
74 options: AgendaOptions = AgendaOptions()
75 ) -> [AgendaDay] {
76 (start..<(start + days)).map { day in
77 var items: [AgendaItem] = []
78 for source in sources { items += entries(source, day: day, today: today, options: options) }
79 let isToday = day == today
80 if (isToday || days == 1), items.contains(where: { $0.timeOfDay != nil }) {
81 items = grid(day: day, isToday: isToday, now: now, options: options) + items
82 }
83 return AgendaDay(day: day, isToday: isToday, header: header(day), items: sort(items))
84 }
85 }
86
87 /// `org-agenda-get-day-entries` with the default entry types.
88 static func entries(_ source: AgendaSource, day: Int, today: Int, options: AgendaOptions) -> [AgendaItem] {
89 let deadlines = self.deadlines(source, day: day, today: today, options: options)
90 return deadlines + scheduled(source, day: day, today: today, options: options) + blocks(source, day: day, options: options)
91 + timestamps(source, day: day, today: today, options: options)
92 }
93
94 // MARK: - Collectors
95
96 static func deadlines(_ source: AgendaSource, day current: Int, today: Int, options: AgendaOptions) -> [AgendaItem] {
97 let isToday = current == today
98 var items: [AgendaItem] = []
99 for heading in source.headings {
100 guard !heading.skipped, let (s, offset) = heading.deadline, let deadline = Days.absolute(of: s) else { continue }
101 let repeat_ = current <= today ? deadline : (Days.closest(s, to: current, prefer: .future) ?? deadline)
102 let diff = deadline - current
103 let warningDays = Days.warningDays(s, delay: false, defaultDays: options.deadlineWarningDays)
104 if current != deadline, current != repeat_ {
105 if !isToday { continue }
106 if deadline > current {
107 if diff > warningDays { continue }
108 } else if 10000 < -diff {
109 continue
110 }
111 }
112 if heading.isDone, deadline != current { continue }
113 let time: Dotime? = current != deadline && current != repeat_ ? nil : (timeIn(s).map { .string($0) } ?? .headline)
114 let extra: String
115 if isToday, deadline < today {
116 extra = String(format: "%2d d. ago: ", -diff)
117 } else if isToday, deadline > today {
118 extra = String(format: "In %3d d.: ", diff)
119 } else {
120 extra = "Deadline: "
121 }
122 let upcoming = isToday && deadline > today
123 items.append(format(
124 source, heading, kind: upcoming ? .upcomingDeadline : .deadline, marker: offset, extra: extra,
125 dotime: time, removing: nil, trailing: options.gridTrailing, urgency: { (isToday ? -diff : 0) + $0 }
126 ))
127 }
128 return items
129 }
130
131 static func scheduled(_ source: AgendaSource, day current: Int, today: Int, options: AgendaOptions) -> [AgendaItem] {
132 let isToday = current == today
133 var items: [AgendaItem] = []
134 for heading in source.headings {
135 guard !heading.skipped, let (s, offset) = heading.scheduled, let schedule = Days.absolute(of: s) else { continue }
136 let repeat_ = current <= today ? schedule : (Days.closest(s, to: current, prefer: .future) ?? schedule)
137 let diff = current - schedule
138 let past = schedule < today
139 let delay = Days.warningDays(s, delay: true, defaultDays: 0)
140 if (delay > 0 && diff < delay) || diff > 10000 || schedule > current
141 || (current != schedule && current != today && current != repeat_) {
142 continue
143 }
144 if heading.isDone, schedule != current { continue }
145 let time: Dotime? = current != schedule && current != repeat_ ? nil : (timeIn(s).map { .string($0) } ?? .headline)
146 let extra = isToday && past ? String(format: "Sched.%2dx: ", diff) : "Scheduled: "
147 items.append(format(
148 source, heading, kind: past ? .pastScheduled : .scheduled, marker: offset, extra: extra,
149 dotime: time, removing: nil, trailing: options.gridTrailing, urgency: { 99 + diff + $0 }
150 ))
151 }
152 return items
153 }
154
155 static func blocks(_ source: AgendaSource, day current: Int, options: AgendaOptions) -> [AgendaItem] {
156 var items: [AgendaItem] = []
157 for block in source.blocks {
158 guard let startDay = Days.absolute(of: block.start), let endDay = Days.absolute(of: block.end),
159 current >= startDay, endDay >= current else { continue }
160 let heading = source.headings[block.heading]
161 let extra = startDay == endDay ? "" : "(\(current - startDay + 1)/\(endDay - startDay + 1)): "
162 let dotime: Dotime?
163 if startDay == current, endDay == current {
164 dotime = .string("<\(block.start)>--<\(block.end)>")
165 } else if startDay == current {
166 dotime = .string("<\(block.start)>")
167 } else if endDay == current {
168 dotime = .string("<\(block.end)>")
169 } else {
170 dotime = nil
171 }
172 items.append(format(source, heading, kind: .block, marker: block.marker, extra: extra, dotime: dotime, removing: nil, trailing: options.gridTrailing, urgency: { $0 }))
173 }
174 return items
175 }
176
177 static let repeating = try! NSRegularExpression(pattern: "^<[0-9]+-[0-9]+-[0-9]+[^>\\n]+?\\+[0-9]+[hdwmy]>")
178 static let stampBoth = try! NSRegularExpression(pattern: "^[\\[<](\(AgendaSource.tsInternal))[\\]>]")
179 static let stampActive = try! NSRegularExpression(pattern: "<(\(AgendaSource.tsInternal))>")
180 static let stampAny = try! NSRegularExpression(pattern: "[\\[<](\(AgendaSource.tsInternal))[\\]>]")
181
182 static func timestamps(_ source: AgendaSource, day current: Int, today: Int, options: AgendaOptions) -> [AgendaItem] {
183 let date = Days.date(current)
184 let literal = String(format: "<%04d-%02d-%02d", date.year, date.month, date.day)
185 var items: [AgendaItem] = []
186 for stamp in source.stamps {
187 let rest = stamp.rest as NSString
188 let all = NSRange(location: 0, length: rest.length)
189 let timestamp: String
190 if stamp.rest.hasPrefix(literal) {
191 guard let m = stampBoth.firstMatch(in: stamp.rest, range: all) else { continue }
192 timestamp = rest.substring(with: m.range)
193 } else if let m = repeating.firstMatch(in: stamp.rest, range: all) {
194 let repeat_ = rest.substring(with: m.range)
195 guard let past = Days.closest(repeat_, to: current > today ? today : current, prefer: .past) else { continue }
196 let future = current <= today ? past : (Days.closest(repeat_, to: current, prefer: .future) ?? past)
197 if current != past, current != future { continue }
198 timestamp = repeat_
199 } else {
200 continue
201 }
202 let heading = source.headings[stamp.heading]
203 items.append(format(
204 source, heading, kind: .timestamp, marker: stamp.offset, extra: "",
205 dotime: .string(timestamp), removing: stampActive, trailing: options.gridTrailing, urgency: { $0 }
206 ))
207 }
208 return items
209 }
210
211 /// `" HH:MM"` in a planning timestamp: the time and everything after it.
212 static func timeIn(_ s: String) -> String? {
213 guard let r = s.range(of: " [012]?[0-9]:[0-9][0-9]", options: .regularExpression) else { return nil }
214 return String(s[s.index(after: r.lowerBound)...]) + " "
215 }
216
217 // MARK: - Formatting
218
219 enum Dotime {
220 case string(String)
221 /// Look for a time in the heading only.
222 case headline
223 }
224
225 static let tagGroup = try! NSRegularExpression(pattern: "[ \\t]+(:([\\p{L}\\p{N}_@#%:]+):)[ \\t]*$")
226 static let stampTime = try! NSRegularExpression(
227 pattern: "<([0-9]{4}-[0-9]{2}-[0-9]{2} +[\\p{L}\\p{N}_]+ +)([012][0-9]:[0-5][0-9])(-([012][0-9]:[0-5][0-9]))?[^\\n\\r>]*?>(--?<\\1([012][0-9]:[0-5][0-9])>)?"
228 )
229 static let plainTimePart = "((?<![\\p{L}\\p{N}_])[012]?[0-9]((:([0-5][0-9]([AaPp][Mm])?))|([AaPp][Mm]))(?![\\p{L}\\p{N}_]))"
230 static let plainTime = try! NSRegularExpression(pattern: "\(plainTimePart)(--?\(plainTimePart))?")
231 static let timeOfDay = try! NSRegularExpression(
232 pattern: "(?<![\\p{L}\\p{N}_])([012]?[0-9])(?::([0-5][0-9])(am|pm)?|(am|pm))(?![\\p{L}\\p{N}_])",
233 options: .caseInsensitive
234 )
235
236 /// `org-agenda-format-item` with the default agenda prefix ` %i %-12:c%?-12t% s`, then
237 /// `org-agenda-highlight-todo`.
238 static func format(
239 _ source: AgendaSource, _ heading: AgendaSource.Heading, kind: AgendaItem.Kind, marker: Int,
240 extra: String, dotime: Dotime?, removing: NSRegularExpression?, trailing: String, hasTime: Bool = true,
241 urgency: (Int) -> Int
242 ) -> AgendaItem {
243 var txt = heading.head.trimmingCharacters(in: .whitespaces)
244 // `org-agenda-fix-displayed-tags`: the heading's tags are replaced by the full list.
245 let tags = heading.tags
246 if let m = tagGroup.firstMatch(in: txt, range: NSRange(location: 0, length: (txt as NSString).length)) {
247 txt = (txt as NSString).substring(to: m.range.location)
248 }
249 var tagString = ""
250 if !tags.isEmpty {
251 var haveInherited = tags[0].inherited
252 var parts: [String] = []
253 for tag in tags {
254 if haveInherited, !tag.inherited {
255 haveInherited = false
256 parts.append(":" + tag.name)
257 } else {
258 parts.append(tag.name)
259 }
260 }
261 tagString = ":" + parts.joined(separator: ":") + (haveInherited ? "::" : ":")
262 }
263
264 let timed = timeFields(&txt, tagString: tagString, dotime: dotime, trailing: trailing, removeTimes: hasTime)
265 if let removing {
266 while let m = removing.firstMatch(in: txt, range: NSRange(location: 0, length: (txt as NSString).length)) {
267 txt = (txt as NSString).replacingCharacters(in: m.range, with: "")
268 }
269 }
270 let category = heading.category
271 // ` %i %-12:c%?-12t% s` in the agenda, ` %i %-12:c` in TODO and tags lists.
272 let prefix = " " + pad(category.isEmpty ? "" : category + ":", 12)
273 + (hasTime ? (timed.time.isEmpty ? "" : pad(timed.time, 12)) + (extra.isEmpty ? "" : extra + " ") : "")
274 txt = highlightTodo(txt, keywords: source.keywords)
275 let priority = Self.priority(prefix + txt, source.priorities)
276 return AgendaItem(
277 kind: kind, path: source.path, headingOffset: heading.start, headingLine: heading.line, markerOffset: marker, category: category,
278 timeOfDay: timed.timeOfDay, time: timed.time, extra: extra, text: txt, tags: tags.map(\.name),
279 todo: heading.todo, isDone: heading.isDone, urgency: urgency(priority),
280 line: prefix + txt + (tagString.isEmpty ? "" : " " + tagString)
281 )
282 }
283
284 /// The time-of-day part of `org-agenda-format-item`: finds the time, removes it from the
285 /// text, and formats the `%t` field.
286 static func timeFields(_ txt: inout String, tagString: String, dotime: Dotime?, trailing: String, removeTimes: Bool = true) -> (timeOfDay: Int?, time: String) {
287 guard let dotime else { return (nil, "") }
288 let full = tagString.isEmpty ? txt : txt + " " + tagString
289 let withoutStamps = stampAny.stringByReplacingMatches(in: full, range: NSRange(location: 0, length: (full as NSString).length), withTemplate: "")
290 let containing: String
291 switch dotime {
292 case .string(let s): containing = s + withoutStamps
293 case .headline: containing = withoutStamps
294 }
295 guard let timeOfDay = time(of: containing) else { return (nil, "") }
296 let ns = containing as NSString
297 let all = NSRange(location: 0, length: ns.length)
298 var start: String?
299 var end: String?
300 if let m = stampTime.firstMatch(in: containing, range: all) {
301 start = ns.substring(with: m.range(at: 2))
302 let endGroup = m.range(at: 3).location != NSNotFound ? 4 : 6
303 if m.range(at: endGroup).location != NSNotFound { end = ns.substring(with: m.range(at: endGroup)) }
304 if removeTimes { removeTime(ns.substring(with: m.range), from: &txt) }
305 } else if let m = plainTime.firstMatch(in: containing, range: all) {
306 start = ns.substring(with: m.range(at: 1))
307 if m.range(at: 8).location != NSNotFound { end = ns.substring(with: m.range(at: 8)) }
308 if removeTimes { removeTime(ns.substring(with: m.range), from: &txt) }
309 }
310 let startText = start.flatMap(formattedTime).map { String(repeating: " ", count: max(0, 5 - $0.count)) + $0 }
311 let endText = end.flatMap(formattedTime)
312 let time: String
313 if let startText, let endText {
314 time = startText + "-" + endText
315 } else if let startText {
316 time = startText + trailing
317 } else {
318 time = ""
319 }
320 return (timeOfDay, time)
321 }
322
323 /// `org-agenda-remove-times-when-in-prefix`.
324 static func removeTime(_ timeString: String, from txt: inout String) {
325 let ns = txt as NSString
326 let regex = try! NSRegularExpression(pattern: NSRegularExpression.escapedPattern(for: timeString) + " *")
327 guard let m = regex.firstMatch(in: txt, range: NSRange(location: 0, length: ns.length)) else { return }
328 if NSMaxRange(m.range) < ns.length, ns.character(at: NSMaxRange(m.range)) == 93 { return }
329 txt = ns.replacingCharacters(in: m.range, with: "")
330 }
331
332 /// `org-get-time-of-day` as a number.
333 static func time(of s: String) -> Int? {
334 let ns = s as NSString
335 guard let m = timeOfDay.firstMatch(in: s, range: NSRange(location: 0, length: ns.length)) else { return nil }
336 var hours = Int(ns.substring(with: m.range(at: 1)))!
337 let minutes = m.range(at: 2).location != NSNotFound ? Int(ns.substring(with: m.range(at: 2)))! : 0
338 let ampmRange = m.range(at: 3).location != NSNotFound ? m.range(at: 3) : m.range(at: 4)
339 if ampmRange.location != NSNotFound {
340 let am = ns.substring(with: ampmRange).lowercased() == "am"
341 hours = hours == 12 ? (am ? 0 : 12) : hours + (am ? 0 : 12)
342 }
343 return hours * 100 + minutes
344 }
345
346 /// `org-get-time-of-day` with `overtime`: `H:MM`, or `+H:MM` past midnight.
347 static func formattedTime(_ s: String) -> String? {
348 guard let value = time(of: s) else { return nil }
349 let hours = value / 100
350 let minutes = value % 100
351 if hours > 24 || (hours == 24 && minutes > 0) { return String(format: "+%d:%02d", hours - 24, minutes) }
352 return String(format: "%d:%02d", hours, minutes)
353 }
354
355 /// `format "%-Ns"`: pads to a display width.
356 static func pad(_ s: String, _ width: Int) -> String {
357 s + String(repeating: " ", count: max(0, width - displayWidth(s)))
358 }
359
360 /// `org-agenda-highlight-todo` with `org-agenda-todo-keyword-format` `%-1s`: the spaces
361 /// after a leading TODO keyword become one.
362 static func highlightTodo(_ txt: String, keywords: [String]) -> String {
363 let dots = txt.prefix { $0 == "." }
364 let rest = txt.dropFirst(dots.count)
365 for keyword in keywords.sorted(by: { $0.count > $1.count }) where rest.hasPrefix(keyword) {
366 let after = rest.dropFirst(keyword.count)
367 guard after.first == " " else { continue }
368 return dots + keyword + " " + after.drop { $0 == " " }
369 }
370 return txt
371 }
372
373 /// `org-get-priority`.
374 static func priority(_ s: String, _ priorities: Priorities) -> Int {
375 func value(_ p: String) -> Int {
376 p.allSatisfy(\.isNumber) ? Int(p)! : Int(p.unicodeScalars.first!.value)
377 }
378 let lowest = value(priorities.lowest)
379 if let r = s.range(of: "\\[#([A-Z]|[0-9]|[1-5][0-9]|6[0-4])\\]", options: .regularExpression) {
380 return 1000 * (lowest - value(String(s[r].dropFirst(2).dropLast())))
381 }
382 return 1000 * (lowest - value(priorities.default))
383 }
384
385 // MARK: - Grid, sorting, headers
386
387 /// `org-agenda-add-time-grid-maybe`.
388 static func grid(day: Int, isToday: Bool, now: (hour: Int, minute: Int), options: AgendaOptions) -> [AgendaItem] {
389 func item(_ kind: AgendaItem.Kind, _ text: String, _ dotime: String) -> AgendaItem {
390 var txt = text
391 let timed = timeFields(&txt, tagString: "", dotime: .string(dotime), trailing: options.gridTrailing)
392 return AgendaItem(
393 kind: kind, path: nil, headingOffset: nil, headingLine: nil, markerOffset: nil, category: "", timeOfDay: timed.timeOfDay,
394 time: timed.time, extra: "", text: txt, tags: [], todo: nil, isDone: false, urgency: 0,
395 line: " " + pad("", 12) + pad(timed.time, 12) + txt
396 )
397 }
398 var new = options.gridTimes.reversed().map { t in
399 item(.timeGrid, options.gridLine, String(format: "%02d:%02d", t / 100, t % 100))
400 }
401 if isToday {
402 new.insert(item(.currentTime, options.currentTimeLine, String(format: "%02d:%02d ", now.hour, now.minute)), at: 0)
403 }
404 return new
405 }
406
407 /// `org-entries-lessp` with `(habit-down time-up urgency-down category-keep)`, stably.
408 static func sort(_ items: [AgendaItem]) -> [AgendaItem] {
409 items.enumerated().sorted { a, b in
410 let ta = a.element.timeOfDay ?? 9901
411 let tb = b.element.timeOfDay ?? 9901
412 if ta != tb { return ta < tb }
413 if a.element.urgency != b.element.urgency { return a.element.urgency > b.element.urgency }
414 return a.offset < b.offset
415 }.map(\.element)
416 }
417
418 static let dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
419 static let monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
420
421 /// `org-agenda-format-date-aligned`.
422 public static func header(_ day: Int) -> String {
423 let date = Days.date(day)
424 let weekday = Days.weekday(day)
425 let week = weekday == 1 ? String(format: " W%02d", Days.isoWeek(day)) : ""
426 return pad(dayNames[weekday], 10) + String(format: " %2d ", date.day) + monthNames[date.month - 1] + String(format: " %4d", date.year) + week
427 }
428}