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