Sources/OrgCore/Agenda/Agenda.swift

30f6716c5b85f009c8cee977f3e5e4e4b5df3d09
orgstar/Sources/OrgCore/Agenda/Agenda.swift history · blame · raw

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