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