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