krz/orgstar

A native macOS editor for org-mode files. editor org-mode swift

Sources/OrgCore/Agenda/Agenda.swift

15f6b0709d88971fb62ed432c3e5b8032643670a
orgstar/Sources/OrgCore/Agenda/Agenda.swift history · blame · raw

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