Sources/OrgCore/Agenda/Agenda.swift

b4eeefea9b0dbf6952995d9accda575f1b2b5060
orgstar/Sources/OrgCore/Agenda/Agenda.swift

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