Sources/OrgCore/Agenda/Agenda.swift

848c7b130274052f194a17fccd4e33e6bb30851d
orgstar/Sources/OrgCore/Agenda/Agenda.swift history · blame · raw

630 lines · 32938 bytes

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