Sources/OrgCore/Agenda/Agenda.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Sources/OrgCore/Agenda/Agenda.swift history · blame · raw

705 lines · 37430 bytes

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