Sources/OrgCore/Agenda/Agenda.swift

241525746419a10a1816afce1593ecb62ebea46b
orgstar/Sources/OrgCore/Agenda/Agenda.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form