Sources/OrgCore/Agenda/Agenda.swift

af140c9251eac8434e572e9dda587c4573b64e6b
orgstar/Sources/OrgCore/Agenda/Agenda.swift

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