Sources/OrgCore/Agenda/Agenda.swift

524b5afe95ec3f3e3d1daba761a9e181f09cf88a
orgstar/Sources/OrgCore/Agenda/Agenda.swift history · blame · raw

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