Sources/OrgCore/Agenda/DiarySexp.swift

design-themes-widgets
orgstar/Sources/OrgCore/Agenda/DiarySexp.swift history · blame · raw

333 lines · 18036 bytes

  1import Foundation
  2
  3/// Diary sexps, `%%(…)` lines and `<%%(…)>` timestamps: `org-diary-sexp-entry` with the
  4/// calendar, diary-lib and org functions agenda files use. A sexp that uses anything else, or
  5/// signals an error, doesn't apply, as Emacs reports a bad sexp and moves on.
  6public enum DiarySexp {
  7    /// The entries `sexp` gives on `day` for a diary line whose text is `entry`, or nil where
  8    /// it doesn't apply.
  9    public static func entries(_ sexp: Sexp, entry: String, day: Int) -> [String]? {
 10        let lisp = interpreter(day: day, entry: entry)
 11        guard let result = try? lisp.eval(sexp), !Elisp.isNil(result) else { return nil }
 12        switch result {
 13        case .string(let s): return s.components(separatedBy: "; ")
 14        case .dotted(let items, .string(let s)) where items.count == 1: return [s]
 15        case .list(let items) where items.first?.string != nil: return items.map { Elisp.printed($0) }
 16        default: return [entry]
 17        }
 18    }
 19
 20    /// Whether `sexp` applies on `day`, for diary timestamps.
 21    public static func matches(_ sexp: Sexp, day: Int) -> Bool {
 22        entries(sexp, entry: "", day: day) != nil
 23    }
 24
 25    static func interpreter(day: Int, entry: String) -> Elisp {
 26        let lisp = Elisp()
 27        lisp.set("date", gregorian(day))
 28        lisp.set("entry", .string(entry))
 29        lisp.set("calendar-date-style", .symbol("american"))
 30        define(lisp)
 31        return lisp
 32    }
 33
 34    /// `(MONTH DAY YEAR)`.
 35    static func gregorian(_ day: Int) -> Sexp {
 36        let date = Days.date(day)
 37        return .list([.integer(date.month), .integer(date.day), .integer(date.year)])
 38    }
 39
 40    /// A number from Lisp used in date arithmetic, within what that arithmetic handles.
 41    static func bounded(_ v: Sexp) throws -> Int {
 42        let i = try Elisp.int(v)
 43        guard (-100_000_000...100_000_000).contains(i) else { throw Elisp.Unsupported(what: "date number \(i)") }
 44        return i
 45    }
 46
 47    static func parts(_ date: Sexp) throws -> (month: Int, day: Int, year: Int) {
 48        let items = try Elisp.elements(date)
 49        guard items.count == 3 else { throw Elisp.Signal(message: "Bad date \(date.description)") }
 50        return (try bounded(items[0]), try bounded(items[1]), try bounded(items[2]))
 51    }
 52
 53    static func absolute(_ date: Sexp) throws -> Int {
 54        let d = try parts(date)
 55        return Days.absolute(year: d.year, month: d.month, day: d.day)
 56    }
 57
 58    static func isLeap(_ year: Int) -> Bool { year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) }
 59
 60    static func lastDay(month: Int, year: Int) throws -> Int {
 61        guard (1...12).contains(month) else { throw Elisp.Signal(message: "Args out of range: \(month)") }
 62        return month == 2 ? (isLeap(year) ? 29 : 28) : [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1]
 63    }
 64
 65    /// `calendar-nth-named-absday`.
 66    static func nthNamedAbsday(_ n: Int, _ dayname: Int, _ month: Int, _ year: Int, _ day: Int?) throws -> Int {
 67        func onOrBefore(_ date: Int) -> Int { date - (date - dayname) % 7 }
 68        if n > 0 {
 69            return 7 * (n - 1) + onOrBefore(6 + Days.absolute(year: year, month: month, day: day ?? 1))
 70        }
 71        return 7 * (n + 1) + onOrBefore(Days.absolute(year: year, month: month, day: try day ?? lastDay(month: month, year: year)))
 72    }
 73
 74    /// `holiday-easter-etc-abs`.
 75    static func easter(_ year: Int) -> Int {
 76        let century = year / 100 + 1
 77        let shiftedEpact = (14 + 11 * (year % 19) - (3 * century) / 4 + (5 + 8 * century) / 25 + 30 * century) % 30
 78        let adjustedEpact = shiftedEpact == 0 || (shiftedEpact == 1 && 10 < year % 19) ? shiftedEpact + 1 : shiftedEpact
 79        let paschalMoon = Days.absolute(year: year, month: 4, day: 19) - adjustedEpact
 80        let date = paschalMoon + 7
 81        return date - date % 7
 82    }
 83
 84    /// `calendar-check-holidays` with the holidays of Emacs's default `calendar-holidays` that
 85    /// follow fixed rules: `holiday-general-holidays` (the United States') and
 86    /// `holiday-christian-holidays` without `calendar-christian-all-holidays-flag`.
 87    static func holidays(_ day: Int) -> [String] {
 88        let year = Days.date(day).year
 89        func fixed(_ month: Int, _ d: Int) -> Int { Days.absolute(year: year, month: month, day: d) }
 90        func float(_ month: Int, _ dayname: Int, _ n: Int) -> Int { (try? nthNamedAbsday(n, dayname, month, year, nil)) ?? 0 }
 91        let easter = easter(year)
 92        let list: [(Int, String)] = [
 93            (fixed(1, 1), "New Year's Day"), (float(1, 1, 3), "Martin Luther King Day"), (fixed(2, 2), "Groundhog Day"),
 94            (fixed(2, 14), "Valentine's Day"), (float(2, 1, 3), "President's Day"), (fixed(3, 17), "St. Patrick's Day"),
 95            (fixed(4, 1), "April Fools' Day"), (float(5, 0, 2), "Mother's Day"), (float(5, 1, -1), "Memorial Day"),
 96            (fixed(6, 14), "Flag Day"), (float(6, 0, 3), "Father's Day"), (fixed(7, 4), "Independence Day"),
 97            (float(9, 1, 1), "Labor Day"), (float(10, 1, 2), "Columbus Day"), (fixed(10, 31), "Halloween"),
 98            (fixed(11, 11), "Veteran's Day"), (float(11, 4, 4), "Thanksgiving"),
 99            (easter - 46, "Ash Wednesday"), (easter - 2, "Good Friday"), (easter, "Easter Sunday"), (fixed(12, 25), "Christmas"),
100        ]
101        // `calendar-holiday-list` puts each form's holidays before the earlier ones'.
102        return list.filter { $0.0 == day }.map(\.1).reversed()
103    }
104
105    /// `diary-ordinal-suffix`.
106    static func ordinalSuffix(_ n: Int) throws -> String {
107        if [11, 12, 13].contains(n % 100) || 3 < n % 10 { return "th" }
108        guard n % 10 >= 0 else { throw Elisp.Signal(message: "Args out of range") }
109        return ["th", "st", "nd", "rd"][n % 10]
110    }
111
112    /// `diary-make-date`: arguments in `calendar-date-style` order, as `(MONTH DAY YEAR)`.
113    static func makeDate(_ lisp: Elisp, _ a: Sexp, _ b: Sexp, _ c: Sexp) throws -> [Sexp] {
114        switch try lisp.value("calendar-date-style") {
115        case .symbol("iso"): [b, c, a]
116        case .symbol("european"): [b, a, c]
117        default: [a, b, c]
118        }
119    }
120
121    /// Runs `body` with `calendar-date-style` bound to `iso`, as the `org-` wrappers do.
122    static func iso(_ lisp: Elisp, _ body: () throws -> Sexp) rethrows -> Sexp {
123        try lisp.binding(["calendar-date-style": .symbol("iso")], body)
124    }
125
126    static func optional(_ args: [Sexp], _ i: Int) -> Sexp { i < args.count ? args[i] : .nil }
127
128    /// The calendar functions, which don't depend on the diary entry.
129    static func defineCalendar(_ lisp: Elisp) {
130        func arity(_ args: [Sexp], _ range: ClosedRange<Int>, _ name: String) throws {
131            try Elisp.arity(args, range, name)
132        }
133
134        lisp.define("calendar-extract-month") { _, args in try arity(args, 1...1, "calendar-extract-month"); return .integer(try parts(args[0]).month) }
135        lisp.define("calendar-extract-day") { _, args in try arity(args, 1...1, "calendar-extract-day"); return .integer(try parts(args[0]).day) }
136        lisp.define("calendar-extract-year") { _, args in try arity(args, 1...1, "calendar-extract-year"); return .integer(try parts(args[0]).year) }
137        lisp.define("calendar-absolute-from-gregorian") { _, args in
138            try arity(args, 1...1, "calendar-absolute-from-gregorian")
139            return .integer(try absolute(args[0]))
140        }
141        lisp.define("calendar-gregorian-from-absolute") { _, args in
142            try arity(args, 1...1, "calendar-gregorian-from-absolute")
143            return gregorian(try bounded(args[0]))
144        }
145        lisp.define("calendar-day-of-week") { _, args in
146            try arity(args, 1...1, "calendar-day-of-week")
147            return .integer(Days.weekday(try absolute(args[0])))
148        }
149        lisp.define("calendar-leap-year-p") { _, args in
150            try arity(args, 1...1, "calendar-leap-year-p")
151            return Elisp.bool(isLeap(try Elisp.int(args[0])))
152        }
153        lisp.define("calendar-last-day-of-month") { _, args in
154            try arity(args, 2...2, "calendar-last-day-of-month")
155            return .integer(try lastDay(month: try bounded(args[0]), year: try bounded(args[1])))
156        }
157        lisp.define("calendar-date-equal") { _, args in
158            try arity(args, 2...2, "calendar-date-equal")
159            let a = try parts(args[0])
160            let b = try parts(args[1])
161            return Elisp.bool(a == b)
162        }
163        lisp.define("calendar-day-number") { _, args in
164            try arity(args, 1...1, "calendar-day-number")
165            let d = try parts(args[0])
166            return .integer(Days.absolute(year: d.year, month: d.month, day: d.day) - Days.absolute(year: d.year, month: 1, day: 0))
167        }
168        lisp.define("calendar-nth-named-absday") { _, args in
169            try arity(args, 4...5, "calendar-nth-named-absday")
170            let day = Elisp.isNil(optional(args, 4)) ? nil : try bounded(args[4])
171            return .integer(try nthNamedAbsday(try bounded(args[0]), try bounded(args[1]), try bounded(args[2]), try bounded(args[3]), day))
172        }
173        lisp.define("calendar-nth-named-day") { lisp, args in
174            gregorian(try bounded(try lisp.callNamed("calendar-nth-named-absday", args)))
175        }
176        lisp.define("calendar-iso-from-absolute") { _, args in
177            try arity(args, 1...1, "calendar-iso-from-absolute")
178            let day = try bounded(args[0])
179            let thursday = day - (Days.weekday(day) + 6) % 7 + 3
180            return .list([.integer(Days.isoWeek(day)), .integer(Days.weekday(day)), .integer(Days.date(thursday).year)])
181        }
182        lisp.define("calendar-check-holidays") { _, args in
183            try arity(args, 1...1, "calendar-check-holidays")
184            return Elisp.list(holidays(try absolute(args[0])).map(Sexp.string))
185        }
186    }
187
188    static func define(_ lisp: Elisp) {
189        func date() throws -> Sexp { try lisp.value("date") }
190        func entry() throws -> Sexp { try lisp.value("entry") }
191        func arity(_ args: [Sexp], _ range: ClosedRange<Int>, _ name: String) throws {
192            try Elisp.arity(args, range, name)
193        }
194
195        defineCalendar(lisp)
196        lisp.define("diary-ordinal-suffix") { _, args in
197            try arity(args, 1...1, "diary-ordinal-suffix")
198            return .string(try ordinalSuffix(try Elisp.int(args[0])))
199        }
200        lisp.define("diary-make-date") { lisp, args in
201            try arity(args, 3...3, "diary-make-date")
202            return .list(try makeDate(lisp, args[0], args[1], args[2]))
203        }
204        lisp.define("diary-date") { lisp, args in
205            try arity(args, 3...4, "diary-date")
206            let wanted = try makeDate(lisp, args[0], args[1], args[2])
207            let d = try parts(try date())
208            for (spec, actual) in zip(wanted, [d.month, d.day, d.year]) {
209                let holds = switch spec {
210                case .symbol("t"): true
211                case .list(let items): items.contains(.integer(actual))
212                case .integer(let i): i == actual
213                default: false
214                }
215                if !holds { return .nil }
216            }
217            return Elisp.cons(optional(args, 3), try entry())
218        }
219        lisp.define("diary-block") { lisp, args in
220            try arity(args, 6...7, "diary-block")
221            let first = try absolute(.list(try makeDate(lisp, args[0], args[1], args[2])))
222            let last = try absolute(.list(try makeDate(lisp, args[3], args[4], args[5])))
223            let d = try absolute(try date())
224            return first <= d && d <= last ? Elisp.cons(optional(args, 6), try entry()) : .nil
225        }
226        lisp.define("diary-float") { _, args in
227            try arity(args, 3...5, "diary-float")
228            let month = args[0]
229            let dayname = try bounded(args[1])
230            let n = try bounded(args[2])
231            let day = Elisp.isNil(optional(args, 3)) ? nil : try bounded(args[3])
232            let current = try absolute(try date())
233            guard dayname == Days.weekday(current) else { return .nil }
234            let d = Days.date(current)
235            let limit = try nthNamedAbsday(-n, dayname, d.month, d.year, d.day)
236            let lastAbs = n > 0 ? limit : limit + 6
237            let firstAbs = n > 0 ? limit - 6 : limit
238            let first = Days.date(firstAbs)
239            let last = Days.date(lastAbs)
240            func monthMatches(_ m: Int) -> Bool {
241                switch month {
242                case .symbol("t"): true
243                case .list(let items): items.contains(.integer(m))
244                case .integer(let i): i == m
245                default: false
246                }
247            }
248            func base(_ m: Int, _ y: Int) throws -> Int { try day ?? (n > 0 ? 1 : lastDay(month: m, year: y)) }
249            let applies: Bool
250            if first.month == last.month {
251                let b = try base(first.month, first.year)
252                applies = monthMatches(first.month) && first.day <= b && b <= last.day
253            } else {
254                let firstBase = try base(first.month, first.year)
255                let lastBase = try base(last.month, last.year)
256                applies = (first.year < last.year || (first.year == last.year && first.month < last.month))
257                    && ((monthMatches(first.month) && first.day <= firstBase) || (monthMatches(last.month) && lastBase <= last.day))
258            }
259            return applies ? Elisp.cons(optional(args, 4), try entry()) : .nil
260        }
261        lisp.define("diary-anniversary") { lisp, args in
262            try arity(args, 2...4, "diary-anniversary")
263            let made = try makeDate(lisp, args[0], args[1], optional(args, 2))
264            var dd = try bounded(made[1])
265            var mm = try bounded(made[0])
266            let y = try parts(try date()).year
267            let diff = Elisp.isNil(made[2]) ? 100 : y - (try bounded(made[2]))
268            if mm == 2, dd == 29, !isLeap(y) {
269                mm = 3
270                dd = 1
271            }
272            let d = try parts(try date())
273            guard diff > 0, (mm, dd, y) == (d.month, d.day, d.year) else { return .nil }
274            return Elisp.cons(optional(args, 3), .string(try Elisp.format([try entry(), .integer(diff), .string(try ordinalSuffix(diff))])))
275        }
276        lisp.define("diary-cyclic") { lisp, args in
277            try arity(args, 4...5, "diary-cyclic")
278            let n = try Elisp.int(args[0])
279            guard n > 0 else { throw Elisp.Signal(message: "Day count must be positive") }
280            let diff = try absolute(try date()) - (try absolute(.list(try makeDate(lisp, args[1], args[2], args[3]))))
281            let cycle = diff / n
282            guard diff >= 0, diff % n == 0 else { return .nil }
283            return Elisp.cons(optional(args, 4), .string(try Elisp.format([try entry(), .integer(cycle), .string(try ordinalSuffix(cycle))])))
284        }
285        lisp.define("diary-remind") { lisp, args in
286            try arity(args, 2...3, "diary-remind")
287            var days = args[1]
288            if case .integer(let n) = days, n < 0 {
289                guard n >= -Elisp.lengthLimit else { throw Elisp.Signal(message: "Too many days for diary-remind") }
290                days = Elisp.list((1...(-n)).map { .integer($0) })
291            }
292            func remind(_ days: Sexp) throws -> Sexp {
293                let applies = try lisp.eval(args[0])
294                if !Elisp.isNil(applies) { return applies }
295                if case .integer(let n) = days {
296                    let shifted = gregorian(try absolute(try date()) + (try bounded(.integer(n))))
297                    var found = try lisp.binding(["date": shifted]) { try lisp.eval(args[0]) }
298                    guard !Elisp.isNil(found) else { return .nil }
299                    if case .dotted = found { found = try Elisp.cdr(found) } else if case .list = found { found = try Elisp.cdr(found) }
300                    let span = n % 7 == 0 ? String(format: "%d week%@", n / 7, n == 7 ? "" : "s") : String(format: "%d day%@", n, n == 1 ? "" : "s")
301                    return .string("Reminder: Only " + span + " until " + Elisp.printed(found))
302                }
303                guard case .list(let items) = days, let first = items.first else { return .nil }
304                let head = try remind(first)
305                return Elisp.isNil(head) ? try remind(Elisp.list(Array(items.dropFirst()))) : head
306            }
307            return try remind(days)
308        }
309
310        lisp.define("org-anniversary") { lisp, args in try iso(lisp) { try lisp.callNamed("diary-anniversary", args) } }
311        lisp.define("org-cyclic") { lisp, args in try iso(lisp) { try lisp.callNamed("diary-cyclic", args) } }
312        lisp.define("org-block") { lisp, args in try iso(lisp) { try lisp.callNamed("diary-block", args) } }
313        lisp.define("org-date") { lisp, args in try iso(lisp) { try lisp.callNamed("diary-date", args) } }
314        lisp.define("org-calendar-holiday") { _, _ in
315            let names = holidays(try absolute(try date()))
316            return names.isEmpty ? .nil : .string(names.joined(separator: "; "))
317        }
318        lisp.define("org-class") { _, args in
319            try arity(args, 7...Int.max, "org-class")
320            let ints = try args.prefix(7).map(bounded)
321            let first = Days.absolute(year: ints[0], month: ints[1], day: ints[2])
322            let last = Days.absolute(year: ints[3], month: ints[4], day: ints[5])
323            let d = try absolute(try date())
324            let skip = Array(args.dropFirst(7))
325            let week = Days.isoWeek(d)
326            guard first <= d, d <= last, Days.weekday(d) == ints[6], !skip.contains(.integer(week)) else { return .nil }
327            // `holidays' skips every holiday, a holiday's name that one.
328            let names = skip.isEmpty ? [] : holidays(d)
329            if !names.isEmpty, skip.contains(.symbol("holidays")) || names.contains(where: { skip.contains(.string($0)) }) { return .nil }
330            return try entry()
331        }
332    }
333}