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