Sources/OrgCore/Agenda/Agenda.swift
559 lines · 29557 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 sexp
12 case timeGrid
13 case currentTime
14 case todo
15 case tagsMatch = "tagsmatch"
16 case search
17 /// Log mode: a closed entry, a clock line, a state change.
18 case closed, clock, state
19 }
20
21 public let kind: Kind
22 public let path: String?
23 /// Start of the entry's heading line.
24 public let headingOffset: Int?
25 /// The heading line as it was read, from its stars, to check the offsets still hold.
26 public let headingLine: String?
27 /// Where org's marker points: the timestamp, or the end of a range.
28 public let markerOffset: Int?
29 public let category: String
30 /// `HHMM`, when the item has a time of day.
31 public let timeOfDay: Int?
32 /// `14:00-15:00`, ` 9:00......`, or empty.
33 public let time: String
34 /// The leader: `Deadline: `, `Sched. 2x: `, `(1/3): `.
35 public let extra: String
36 /// The heading text as shown: TODO keyword, priority, title, without tags.
37 public let text: String
38 public let tags: [String]
39 public let todo: String?
40 public let isDone: Bool
41 public let urgency: Int
42 /// `APPT_WARNTIME`: minutes of warning before the entry's time.
43 public let warntime: Int?
44 /// The habit whose consistency graph goes on the line (scheduled habits).
45 public let habit: Habit?
46 /// The line as org prints it, with one space before the tags.
47 public let line: String
48 /// What `org-agenda-prefix-format` puts before the heading text.
49 public var prefix = ""
50 /// The entry's `Effort` property.
51 public var effort: String?
52 /// Deadlines and scheduled items: the day (as `Days` numbers it) of the timestamp the item
53 /// is for, the repeater's occurrence when the item shows on it.
54 public var planningDay: Int?
55}
56
57public struct AgendaDay: Sendable, Equatable {
58 /// Emacs's absolute day number (`Days`).
59 public let day: Int
60 public let isToday: Bool
61 /// `Monday 5 October 2026 W41`.
62 public let header: String
63 public let items: [AgendaItem]
64}
65
66public struct AgendaOptions: Sendable, Equatable {
67 public var deadlineWarningDays = 14
68 public var gridTimes = [800, 1000, 1200, 1400, 1600, 1800, 2000]
69 public var gridTrailing = " ┄┄┄┄┄ "
70 public var gridLine = "┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄"
71 public var currentTimeLine = "← now ───────────────────────────────────────────────"
72 /// `org-agenda-prefix-format`, by view: `agenda`, `todo`, `tags`, `search`.
73 public var prefixFormat = PrefixFormat.defaults
74 /// Log mode (`l`): closed entries and clocked time on each day.
75 public var logMode = false
76 /// `org-agenda-log-mode-items`.
77 public var logItems: Set<String> = ["closed", "clock"]
78 /// `org-agenda-skip-scheduled-if-done`: done entries' scheduled items are left out even
79 /// on the day they are scheduled.
80 public var skipScheduledIfDone = false
81 /// `org-agenda-skip-deadline-if-done`: done entries' deadlines are left out even on the day due.
82 public var skipDeadlineIfDone = false
83 /// `org-agenda-search-view-always-boolean`: search strings are always `+word -word` snippets.
84 public var searchAlwaysBoolean = false
85 /// `org-agenda-search-view-force-full-words`: search snippets match whole words only.
86 public var searchForceFullWords = false
87
88 public init() {}
89
90 func prefix(_ view: String) -> PrefixFormat {
91 PrefixFormat(prefixFormat[view] ?? PrefixFormat.defaults[view]!)
92 }
93
94 /// What Emacs shows without a graphical display.
95 public static let terminal: AgendaOptions = {
96 var options = AgendaOptions()
97 options.gridTrailing = "......"
98 options.gridLine = "----------------"
99 options.currentTimeLine = "now - - - - - - - - - - - - - - - - - - - - - - - - -"
100 return options
101 }()
102}
103
104/// `org-agenda-list`.
105public enum Agenda {
106 public static func list(
107 _ sources: [AgendaSource], start: Int, days: Int, today: Int, now: (hour: Int, minute: Int),
108 options: AgendaOptions = AgendaOptions()
109 ) -> [AgendaDay] {
110 (start..<(start + days)).map { day in
111 var items: [AgendaItem] = []
112 for source in sources { items += entries(source, day: day, today: today, options: options) }
113 let isToday = day == today
114 if (isToday || days == 1), items.contains(where: { $0.timeOfDay != nil }) {
115 items = grid(day: day, isToday: isToday, now: now, options: options) + items
116 }
117 return AgendaDay(day: day, isToday: isToday, header: header(day), items: sort(items))
118 }
119 }
120
121 /// `org-agenda-get-day-entries` with the default entry types.
122 static func entries(_ source: AgendaSource, day: Int, today: Int, options: AgendaOptions) -> [AgendaItem] {
123 let deadlines = self.deadlines(source, day: day, today: today, options: options)
124 return (options.logMode ? progress(source, day: day, options: options) : []) + deadlines + scheduled(source, day: day, today: today, options: options) + blocks(source, day: day, options: options)
125 + timestamps(source, day: day, today: today, options: options) + sexps(source, day: day, options: options)
126 }
127
128 /// `org-time-string-to-absolute` for a planning timestamp's text: a diary sexp counts on
129 /// `current` when it applies then, and otherwise the entry is skipped.
130 static func planningDay(_ s: String, current: Int) -> (day: Int, sexp: Bool)? {
131 guard s.hasPrefix("%%(") else { return Days.absolute(of: s).map { ($0, false) } }
132 guard let close = s.lastIndex(of: ")"), let (sexp, _) = try? LispReader.readFirst(String(s[s.index(s.startIndex, offsetBy: 2)...close])),
133 DiarySexp.matches(sexp, day: current) else { return nil }
134 return (current, true)
135 }
136
137 // MARK: - Collectors
138
139 static func deadlines(_ source: AgendaSource, day current: Int, today: Int, options: AgendaOptions) -> [AgendaItem] {
140 let isToday = current == today
141 var items: [AgendaItem] = []
142 for heading in source.headings {
143 guard !heading.skipped, let (s, offset) = heading.deadline, let (deadline, sexp) = planningDay(s, current: current) else { continue }
144 let repeat_ = sexp || current <= today ? deadline : (Days.closest(s, to: current, prefer: .future) ?? deadline)
145 let diff = deadline - current
146 let warningDays = Days.warningDays(s, delay: false, defaultDays: options.deadlineWarningDays)
147 if current != deadline, current != repeat_ {
148 if !isToday { continue }
149 if deadline > current {
150 if diff > warningDays { continue }
151 } else if 10000 < -diff {
152 continue
153 }
154 }
155 if heading.isDone, options.skipDeadlineIfDone || deadline != current { continue }
156 let time: Dotime? = current != deadline && current != repeat_ ? nil : (timeIn(s).map { .string($0) } ?? .headline)
157 let extra: String
158 if isToday, deadline < today {
159 extra = String(format: "%2d d. ago: ", -diff)
160 } else if isToday, deadline > today {
161 extra = String(format: "In %3d d.: ", diff)
162 } else {
163 extra = "Deadline: "
164 }
165 let upcoming = isToday && deadline > today
166 var item = format(
167 source, heading, kind: upcoming ? .upcomingDeadline : .deadline, marker: offset, extra: extra,
168 dotime: time, removing: nil, trailing: options.gridTrailing, prefix: options.prefix("agenda"), urgency: { (isToday ? -diff : 0) + $0 }
169 )
170 item.planningDay = current != deadline && current == repeat_ ? repeat_ : deadline
171 items.append(item)
172 }
173 return items
174 }
175
176 static func scheduled(_ source: AgendaSource, day current: Int, today: Int, options: AgendaOptions) -> [AgendaItem] {
177 let isToday = current == today
178 var items: [AgendaItem] = []
179 for heading in source.headings {
180 guard !heading.skipped, let (s, offset) = heading.scheduled, let (schedule, sexp) = planningDay(s, current: current) else { continue }
181 let repeat_ = sexp || current <= today ? schedule : (Days.closest(s, to: current, prefer: .future) ?? schedule)
182 let diff = current - schedule
183 let past = schedule < today
184 let delay = Days.warningDays(s, delay: true, defaultDays: 0)
185 if (delay > 0 && diff < delay) || diff > 10000 || schedule > current
186 || (current != schedule && current != today && current != repeat_) {
187 continue
188 }
189 if heading.isDone, options.skipScheduledIfDone || schedule != current { continue }
190 // org-habit: habits only on today's agenda, and not when done.
191 if heading.isHabit, heading.isDone || !isToday { continue }
192 let time: Dotime? = !heading.isHabit && current != schedule && current != repeat_ ? nil : (timeIn(s).map { .string($0) } ?? .headline)
193 let extra = heading.isHabit ? "" : isToday && past ? String(format: "Sched.%2dx: ", diff) : "Scheduled: "
194 let habit = heading.isHabit ? heading.habit : nil
195 var item = format(
196 source, heading, kind: past ? .pastScheduled : .scheduled, marker: offset, extra: extra,
197 dotime: time, removing: nil, trailing: options.gridTrailing, prefix: options.prefix("agenda"), habit: habit,
198 urgency: { habit?.urgency(today: today) ?? 99 + diff + $0 }
199 )
200 item.planningDay = current != schedule && current == repeat_ ? repeat_ : schedule
201 items.append(item)
202 }
203 return items
204 }
205
206 static func blocks(_ source: AgendaSource, day current: Int, options: AgendaOptions) -> [AgendaItem] {
207 var items: [AgendaItem] = []
208 for block in source.blocks {
209 guard let startDay = Days.absolute(of: block.start), let endDay = Days.absolute(of: block.end),
210 current >= startDay, endDay >= current else { continue }
211 let heading = source.headings[block.heading]
212 let extra = startDay == endDay ? "" : "(\(current - startDay + 1)/\(endDay - startDay + 1)): "
213 let dotime: Dotime?
214 if startDay == current, endDay == current {
215 dotime = .string("<\(block.start)>--<\(block.end)>")
216 } else if startDay == current {
217 dotime = .string("<\(block.start)>")
218 } else if endDay == current {
219 dotime = .string("<\(block.end)>")
220 } else {
221 dotime = nil
222 }
223 items.append(format(source, heading, kind: .block, marker: block.marker, extra: extra, dotime: dotime, removing: nil, trailing: options.gridTrailing, prefix: options.prefix("agenda"), urgency: { $0 }))
224 }
225 return items
226 }
227
228 /// `org-agenda-get-progress`.
229 static func progress(_ source: AgendaSource, day current: Int, options: AgendaOptions) -> [AgendaItem] {
230 let date = Days.date(current)
231 let literal = String(format: "%04d-%02d-%02d", date.year, date.month, date.day)
232 var items: [AgendaItem] = []
233 for entry in source.progress where entry.date == literal {
234 let kind: AgendaItem.Kind
235 let extra: String
236 switch entry.kind {
237 case .closed:
238 guard options.logItems.contains("closed") else { continue }
239 (kind, extra) = (.closed, "Closed: ")
240 case .clock:
241 guard options.logItems.contains("clock") else { continue }
242 (kind, extra) = (.clock, "Clocked: (\(entry.clocked))")
243 case .state:
244 guard options.logItems.contains("state") else { continue }
245 (kind, extra) = (.state, "State: (\(entry.state ?? ""))")
246 }
247 let heading = source.headings[entry.heading]
248 var head = heading.head
249 if let note = entry.note {
250 // Before the tags, as org adds it.
251 if let tags = head.range(of: "([ \\t]+)(:[^ \\n\\t]*?:)[ \\t]*$", options: .regularExpression) {
252 let tagText = head[tags].trimmingCharacters(in: .whitespaces)
253 head = head[..<tags.lowerBound] + " - " + note + " " + tagText
254 } else {
255 head += " - " + note
256 }
257 }
258 items.append(format(
259 source, heading, kind: kind, marker: entry.offset, extra: extra, dotime: .only(entry.timestamp), removing: nil,
260 trailing: options.gridTrailing, prefix: options.prefix("agenda"), head: head, urgency: { _ in 100_000 }
261 ))
262 }
263 return items
264 }
265
266 static let diaryStamp = try! NSRegularExpression(pattern: "^<%%(\\([^>\\n]+\\))([^\\n>]*)>")
267 static let repeating = try! NSRegularExpression(pattern: "^<[0-9]+-[0-9]+-[0-9]+[^>\\n]+?\\+[0-9]+[hdwmy]>")
268 static let stampBoth = try! NSRegularExpression(pattern: "^[\\[<](\(AgendaSource.tsInternal))[\\]>]")
269 static let stampActive = try! NSRegularExpression(pattern: "<(\(AgendaSource.tsInternal))>")
270 static let stampAny = try! NSRegularExpression(pattern: "[\\[<](\(AgendaSource.tsInternal))[\\]>]")
271
272 static func timestamps(_ source: AgendaSource, day current: Int, today: Int, options: AgendaOptions) -> [AgendaItem] {
273 let date = Days.date(current)
274 let literal = String(format: "<%04d-%02d-%02d", date.year, date.month, date.day)
275 var items: [AgendaItem] = []
276 for stamp in source.stamps {
277 let rest = stamp.rest as NSString
278 let all = NSRange(location: 0, length: rest.length)
279 let timestamp: String
280 if stamp.rest.hasPrefix(literal) {
281 guard let m = stampBoth.firstMatch(in: stamp.rest, range: all) else { continue }
282 timestamp = rest.substring(with: m.range)
283 } else if let m = diaryStamp.firstMatch(in: stamp.rest, range: all) {
284 guard let (sexp, _) = try? LispReader.readFirst(rest.substring(with: m.range(at: 1))), DiarySexp.matches(sexp, day: current) else { continue }
285 timestamp = rest.substring(with: m.range)
286 } else if let m = repeating.firstMatch(in: stamp.rest, range: all) {
287 let repeat_ = rest.substring(with: m.range)
288 guard let past = Days.closest(repeat_, to: current > today ? today : current, prefer: .past) else { continue }
289 let future = current <= today ? past : (Days.closest(repeat_, to: current, prefer: .future) ?? past)
290 if current != past, current != future { continue }
291 timestamp = repeat_
292 } else {
293 continue
294 }
295 let heading = source.headings[stamp.heading]
296 items.append(format(
297 source, heading, kind: .timestamp, marker: stamp.offset, extra: "",
298 dotime: .string(timestamp), removing: stampActive, trailing: options.gridTrailing, prefix: options.prefix("agenda"),
299 urgency: { heading.isHabit ? heading.habit?.urgency(today: today) ?? $0 : $0 }
300 ))
301 }
302 return items
303 }
304
305 /// `org-agenda-get-sexps`.
306 static func sexps(_ source: AgendaSource, day current: Int, options: AgendaOptions) -> [AgendaItem] {
307 var items: [AgendaItem] = []
308 for line in source.sexps {
309 guard let results = DiarySexp.entries(line.sexp, entry: line.entry, day: current) else { continue }
310 let heading = source.headings[line.heading]
311 for result in results {
312 let txt = result.contains(where: { !$0.isWhitespace }) ? result : "SEXP entry returned empty string"
313 items.append(format(
314 source, heading, kind: .sexp, marker: line.offset, extra: "", dotime: .headline, removing: nil,
315 trailing: options.gridTrailing, prefix: options.prefix("agenda"), head: txt, attached: false, urgency: { _ in 0 }
316 ))
317 }
318 }
319 return items
320 }
321
322 /// `" HH:MM"` in a planning timestamp: the time and everything after it.
323 static func timeIn(_ s: String) -> String? {
324 guard let r = s.range(of: " [012]?[0-9]:[0-9][0-9]", options: .regularExpression) else { return nil }
325 return String(s[s.index(after: r.lowerBound)...]) + " "
326 }
327
328 // MARK: - Formatting
329
330 enum Dotime {
331 case string(String)
332 /// Look for a time in the heading only.
333 case headline
334 /// In the string only (`org-agenda-search-headline-for-time` nil).
335 case only(String)
336 }
337
338 static let tagGroup = try! NSRegularExpression(pattern: "[ \\t]+(:([\\p{L}\\p{N}_@#%:]+):)[ \\t]*$")
339 static let stampTime = try! NSRegularExpression(
340 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])>)?"
341 )
342 static let plainTimePart = "((?<![\\p{L}\\p{N}_])[012]?[0-9]((:([0-5][0-9]([AaPp][Mm])?))|([AaPp][Mm]))(?![\\p{L}\\p{N}_]))"
343 static let plainTime = try! NSRegularExpression(pattern: "\(plainTimePart)(--?\(plainTimePart))?")
344 static let timeOfDay = try! NSRegularExpression(
345 pattern: "(?<![\\p{L}\\p{N}_])([012]?[0-9])(?::([0-5][0-9])(am|pm)?|(am|pm))(?![\\p{L}\\p{N}_])",
346 options: .caseInsensitive
347 )
348
349 /// `org-agenda-format-item` with the default agenda prefix ` %i %-12:c%?-12t% s`, then
350 /// `org-agenda-highlight-todo`.
351 static func format(
352 _ source: AgendaSource, _ heading: AgendaSource.Heading, kind: AgendaItem.Kind, marker: Int,
353 extra: String, dotime: Dotime?, removing: NSRegularExpression?, trailing: String, prefix prefixFormat: PrefixFormat,
354 head: String? = nil, habit: Habit? = nil, attached: Bool = true, urgency: (Int) -> Int
355 ) -> AgendaItem {
356 var txt = (head ?? heading.head).trimmingCharacters(in: .whitespaces)
357 // `org-agenda-fix-displayed-tags`: the heading's tags are replaced by the full list.
358 let tags = heading.tags
359 if let m = tagGroup.firstMatch(in: txt, range: NSRange(location: 0, length: (txt as NSString).length)) {
360 txt = (txt as NSString).substring(to: m.range.location)
361 }
362 var tagString = ""
363 if !tags.isEmpty {
364 var haveInherited = tags[0].inherited
365 var parts: [String] = []
366 for tag in tags {
367 if haveInherited, !tag.inherited {
368 haveInherited = false
369 parts.append(":" + tag.name)
370 } else {
371 parts.append(tag.name)
372 }
373 }
374 tagString = ":" + parts.joined(separator: ":") + (haveInherited ? "::" : ":")
375 }
376
377 let timed = timeFields(&txt, tagString: tagString, dotime: dotime, trailing: trailing, removeTimes: prefixFormat.hasTime)
378 if let removing {
379 while let m = removing.firstMatch(in: txt, range: NSRange(location: 0, length: (txt as NSString).length)) {
380 txt = (txt as NSString).replacingCharacters(in: m.range, with: "")
381 }
382 }
383 let category = heading.category
384 let prefix = prefixFormat.render([
385 "c": category, "t": timed.time, "s": habit == nil ? extra : "", "l": String(repeating: " ", count: heading.level),
386 "e": heading.properties["EFFORT"] ?? "", "b": breadcrumbs(source, heading), "T": tags.last?.name ?? "",
387 ])
388 txt = highlightTodo(txt, keywords: source.keywords)
389 let priority = Self.priority(prefix + txt, source.priorities)
390 return AgendaItem(
391 kind: kind, path: source.path, headingOffset: attached ? heading.start : nil, headingLine: attached ? heading.line : nil, markerOffset: marker, category: category,
392 timeOfDay: timed.timeOfDay, time: timed.time, extra: extra, text: txt, tags: tags.map(\.name),
393 todo: heading.todo, isDone: heading.isDone, urgency: urgency(priority),
394 warntime: heading.properties["APPT_WARNTIME"].flatMap { Int($0.trimmingCharacters(in: .whitespaces)) }, habit: habit,
395 line: prefix + txt + (tagString.isEmpty ? "" : " " + tagString), prefix: prefix, effort: heading.properties["EFFORT"]
396 )
397 }
398
399 /// `%b`: the outline path above the heading, each title followed by `->`.
400 static func breadcrumbs(_ source: AgendaSource, _ heading: AgendaSource.Heading) -> String {
401 guard let index = source.headings.firstIndex(where: { $0.start == heading.start }) else { return "" }
402 var path: [String] = []
403 var level = heading.level
404 for candidate in source.headings[..<index].reversed() where candidate.level < level {
405 let title = candidate.title.replacingOccurrences(of: "\\[[0-9]+%\\]|\\[[0-9]+/[0-9]+\\]", with: "", options: .regularExpression)
406 path.insert(Links.displayFormat(title).trimmingCharacters(in: .whitespaces), at: 0)
407 level = candidate.level
408 if level == 1 { break }
409 }
410 return path.isEmpty ? "" : path.joined(separator: "->") + "->"
411 }
412
413 /// The time-of-day part of `org-agenda-format-item`: finds the time, removes it from the
414 /// text, and formats the `%t` field.
415 static func timeFields(_ txt: inout String, tagString: String, dotime: Dotime?, trailing: String, removeTimes: Bool = true) -> (timeOfDay: Int?, time: String) {
416 guard let dotime else { return (nil, "") }
417 let full = tagString.isEmpty ? txt : txt + " " + tagString
418 let withoutStamps = stampAny.stringByReplacingMatches(in: full, range: NSRange(location: 0, length: (full as NSString).length), withTemplate: "")
419 let containing: String
420 switch dotime {
421 case .string(let s): containing = s + withoutStamps
422 case .headline: containing = withoutStamps
423 case .only(let s): containing = s
424 }
425 guard let timeOfDay = time(of: containing) else { return (nil, "") }
426 let ns = containing as NSString
427 let all = NSRange(location: 0, length: ns.length)
428 var start: String?
429 var end: String?
430 if let m = stampTime.firstMatch(in: containing, range: all) {
431 start = ns.substring(with: m.range(at: 2))
432 let endGroup = m.range(at: 3).location != NSNotFound ? 4 : 6
433 if m.range(at: endGroup).location != NSNotFound { end = ns.substring(with: m.range(at: endGroup)) }
434 if removeTimes { removeTime(ns.substring(with: m.range), from: &txt) }
435 } else if let m = plainTime.firstMatch(in: containing, range: all) {
436 start = ns.substring(with: m.range(at: 1))
437 if m.range(at: 8).location != NSNotFound { end = ns.substring(with: m.range(at: 8)) }
438 if removeTimes { removeTime(ns.substring(with: m.range), from: &txt) }
439 }
440 let startText = start.flatMap(formattedTime).map { String(repeating: " ", count: max(0, 5 - $0.count)) + $0 }
441 let endText = end.flatMap(formattedTime)
442 let time: String
443 if let startText, let endText {
444 time = startText + "-" + endText
445 } else if let startText {
446 time = startText + trailing
447 } else {
448 time = ""
449 }
450 return (timeOfDay, time)
451 }
452
453 /// `org-agenda-remove-times-when-in-prefix`.
454 static func removeTime(_ timeString: String, from txt: inout String) {
455 let ns = txt as NSString
456 let regex = try! NSRegularExpression(pattern: NSRegularExpression.escapedPattern(for: timeString) + " *")
457 guard let m = regex.firstMatch(in: txt, range: NSRange(location: 0, length: ns.length)) else { return }
458 if NSMaxRange(m.range) < ns.length, ns.character(at: NSMaxRange(m.range)) == 93 { return }
459 txt = ns.replacingCharacters(in: m.range, with: "")
460 }
461
462 /// `org-get-time-of-day` as a number.
463 static func time(of s: String) -> Int? {
464 let ns = s as NSString
465 guard let m = timeOfDay.firstMatch(in: s, range: NSRange(location: 0, length: ns.length)) else { return nil }
466 var hours = Int(ns.substring(with: m.range(at: 1)))!
467 let minutes = m.range(at: 2).location != NSNotFound ? Int(ns.substring(with: m.range(at: 2)))! : 0
468 let ampmRange = m.range(at: 3).location != NSNotFound ? m.range(at: 3) : m.range(at: 4)
469 if ampmRange.location != NSNotFound {
470 let am = ns.substring(with: ampmRange).lowercased() == "am"
471 hours = hours == 12 ? (am ? 0 : 12) : hours + (am ? 0 : 12)
472 }
473 return hours * 100 + minutes
474 }
475
476 /// `org-get-time-of-day` with `overtime`: `H:MM`, or `+H:MM` past midnight.
477 static func formattedTime(_ s: String) -> String? {
478 guard let value = time(of: s) else { return nil }
479 let hours = value / 100
480 let minutes = value % 100
481 if hours > 24 || (hours == 24 && minutes > 0) { return String(format: "+%d:%02d", hours - 24, minutes) }
482 return String(format: "%d:%02d", hours, minutes)
483 }
484
485 /// `format "%-Ns"`: pads to a display width.
486 static func pad(_ s: String, _ width: Int) -> String {
487 s + String(repeating: " ", count: max(0, width - displayWidth(s)))
488 }
489
490 /// `org-agenda-highlight-todo` with `org-agenda-todo-keyword-format` `%-1s`: the spaces
491 /// after a leading TODO keyword become one.
492 static func highlightTodo(_ txt: String, keywords: [String]) -> String {
493 let dots = txt.prefix { $0 == "." }
494 let rest = txt.dropFirst(dots.count)
495 for keyword in keywords.sorted(by: { $0.count > $1.count }) where rest.hasPrefix(keyword) {
496 let after = rest.dropFirst(keyword.count)
497 guard after.first == " " else { continue }
498 return dots + keyword + " " + after.drop { $0 == " " }
499 }
500 return txt
501 }
502
503 /// `org-get-priority`.
504 static func priority(_ s: String, _ priorities: Priorities) -> Int {
505 func value(_ p: String) -> Int {
506 p.allSatisfy(\.isNumber) ? Int(p)! : Int(p.unicodeScalars.first!.value)
507 }
508 let lowest = value(priorities.lowest)
509 if let r = s.range(of: "\\[#([A-Z]|[0-9]|[1-5][0-9]|6[0-4])\\]", options: .regularExpression) {
510 return 1000 * (lowest - value(String(s[r].dropFirst(2).dropLast())))
511 }
512 return 1000 * (lowest - value(priorities.default))
513 }
514
515 // MARK: - Grid, sorting, headers
516
517 /// `org-agenda-add-time-grid-maybe`.
518 static func grid(day: Int, isToday: Bool, now: (hour: Int, minute: Int), options: AgendaOptions) -> [AgendaItem] {
519 func item(_ kind: AgendaItem.Kind, _ text: String, _ dotime: String) -> AgendaItem {
520 var txt = text
521 let timed = timeFields(&txt, tagString: "", dotime: .string(dotime), trailing: options.gridTrailing)
522 return AgendaItem(
523 kind: kind, path: nil, headingOffset: nil, headingLine: nil, markerOffset: nil, category: "", timeOfDay: timed.timeOfDay,
524 time: timed.time, extra: "", text: txt, tags: [], todo: nil, isDone: false, urgency: 0, warntime: nil, habit: nil,
525 line: options.prefix("agenda").render(["t": timed.time]) + txt, prefix: options.prefix("agenda").render(["t": timed.time])
526 )
527 }
528 var new = options.gridTimes.reversed().map { t in
529 item(.timeGrid, options.gridLine, String(format: "%02d:%02d", t / 100, t % 100))
530 }
531 if isToday {
532 new.insert(item(.currentTime, options.currentTimeLine, String(format: "%02d:%02d ", now.hour, now.minute)), at: 0)
533 }
534 return new
535 }
536
537 /// `org-entries-lessp` with `(habit-down time-up urgency-down category-keep)`, stably.
538 static func sort(_ items: [AgendaItem]) -> [AgendaItem] {
539 items.enumerated().sorted { a, b in
540 if (a.element.habit == nil) != (b.element.habit == nil) { return a.element.habit == nil }
541 let ta = a.element.timeOfDay ?? 9901
542 let tb = b.element.timeOfDay ?? 9901
543 if ta != tb { return ta < tb }
544 if a.element.urgency != b.element.urgency { return a.element.urgency > b.element.urgency }
545 return a.offset < b.offset
546 }.map(\.element)
547 }
548
549 static let dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
550 static let monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
551
552 /// `org-agenda-format-date-aligned`.
553 public static func header(_ day: Int) -> String {
554 let date = Days.date(day)
555 let weekday = Days.weekday(day)
556 let week = weekday == 1 ? String(format: " W%02d", Days.isoWeek(day)) : ""
557 return pad(dayNames[weekday], 10) + String(format: " %2d ", date.day) + monthNames[date.month - 1] + String(format: " %4d", date.year) + week
558 }
559}