Sources/OrgCore/Agenda/DiarySexp.swift
325 lines · 17737 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 static func define(_ lisp: Elisp) {
129 func date() throws -> Sexp { try lisp.value("date") }
130 func entry() throws -> Sexp { try lisp.value("entry") }
131 func arity(_ args: [Sexp], _ range: ClosedRange<Int>, _ name: String) throws {
132 try Elisp.arity(args, range, name)
133 }
134
135 lisp.define("calendar-extract-month") { _, args in try arity(args, 1...1, "calendar-extract-month"); return .integer(try parts(args[0]).month) }
136 lisp.define("calendar-extract-day") { _, args in try arity(args, 1...1, "calendar-extract-day"); return .integer(try parts(args[0]).day) }
137 lisp.define("calendar-extract-year") { _, args in try arity(args, 1...1, "calendar-extract-year"); return .integer(try parts(args[0]).year) }
138 lisp.define("calendar-absolute-from-gregorian") { _, args in
139 try arity(args, 1...1, "calendar-absolute-from-gregorian")
140 return .integer(try absolute(args[0]))
141 }
142 lisp.define("calendar-gregorian-from-absolute") { _, args in
143 try arity(args, 1...1, "calendar-gregorian-from-absolute")
144 return gregorian(try bounded(args[0]))
145 }
146 lisp.define("calendar-day-of-week") { _, args in
147 try arity(args, 1...1, "calendar-day-of-week")
148 return .integer(Days.weekday(try absolute(args[0])))
149 }
150 lisp.define("calendar-leap-year-p") { _, args in
151 try arity(args, 1...1, "calendar-leap-year-p")
152 return Elisp.bool(isLeap(try Elisp.int(args[0])))
153 }
154 lisp.define("calendar-last-day-of-month") { _, args in
155 try arity(args, 2...2, "calendar-last-day-of-month")
156 return .integer(try lastDay(month: try bounded(args[0]), year: try bounded(args[1])))
157 }
158 lisp.define("calendar-date-equal") { _, args in
159 try arity(args, 2...2, "calendar-date-equal")
160 let a = try parts(args[0])
161 let b = try parts(args[1])
162 return Elisp.bool(a == b)
163 }
164 lisp.define("calendar-day-number") { _, args in
165 try arity(args, 1...1, "calendar-day-number")
166 let d = try parts(args[0])
167 return .integer(Days.absolute(year: d.year, month: d.month, day: d.day) - Days.absolute(year: d.year, month: 1, day: 0))
168 }
169 lisp.define("calendar-nth-named-absday") { _, args in
170 try arity(args, 4...5, "calendar-nth-named-absday")
171 let day = Elisp.isNil(optional(args, 4)) ? nil : try bounded(args[4])
172 return .integer(try nthNamedAbsday(try bounded(args[0]), try bounded(args[1]), try bounded(args[2]), try bounded(args[3]), day))
173 }
174 lisp.define("calendar-nth-named-day") { lisp, args in
175 gregorian(try bounded(try lisp.callNamed("calendar-nth-named-absday", args)))
176 }
177 lisp.define("calendar-iso-from-absolute") { _, args in
178 try arity(args, 1...1, "calendar-iso-from-absolute")
179 let day = try bounded(args[0])
180 let thursday = day - (Days.weekday(day) + 6) % 7 + 3
181 return .list([.integer(Days.isoWeek(day)), .integer(Days.weekday(day)), .integer(Days.date(thursday).year)])
182 }
183
184 lisp.define("diary-ordinal-suffix") { _, args in
185 try arity(args, 1...1, "diary-ordinal-suffix")
186 return .string(try ordinalSuffix(try Elisp.int(args[0])))
187 }
188 lisp.define("diary-make-date") { lisp, args in
189 try arity(args, 3...3, "diary-make-date")
190 return .list(try makeDate(lisp, args[0], args[1], args[2]))
191 }
192 lisp.define("diary-date") { lisp, args in
193 try arity(args, 3...4, "diary-date")
194 let wanted = try makeDate(lisp, args[0], args[1], args[2])
195 let d = try parts(try date())
196 for (spec, actual) in zip(wanted, [d.month, d.day, d.year]) {
197 let holds = switch spec {
198 case .symbol("t"): true
199 case .list(let items): items.contains(.integer(actual))
200 case .integer(let i): i == actual
201 default: false
202 }
203 if !holds { return .nil }
204 }
205 return Elisp.cons(optional(args, 3), try entry())
206 }
207 lisp.define("diary-block") { lisp, args in
208 try arity(args, 6...7, "diary-block")
209 let first = try absolute(.list(try makeDate(lisp, args[0], args[1], args[2])))
210 let last = try absolute(.list(try makeDate(lisp, args[3], args[4], args[5])))
211 let d = try absolute(try date())
212 return first <= d && d <= last ? Elisp.cons(optional(args, 6), try entry()) : .nil
213 }
214 lisp.define("diary-float") { _, args in
215 try arity(args, 3...5, "diary-float")
216 let month = args[0]
217 let dayname = try bounded(args[1])
218 let n = try bounded(args[2])
219 let day = Elisp.isNil(optional(args, 3)) ? nil : try bounded(args[3])
220 let current = try absolute(try date())
221 guard dayname == Days.weekday(current) else { return .nil }
222 let d = Days.date(current)
223 let limit = try nthNamedAbsday(-n, dayname, d.month, d.year, d.day)
224 let lastAbs = n > 0 ? limit : limit + 6
225 let firstAbs = n > 0 ? limit - 6 : limit
226 let first = Days.date(firstAbs)
227 let last = Days.date(lastAbs)
228 func monthMatches(_ m: Int) -> Bool {
229 switch month {
230 case .symbol("t"): true
231 case .list(let items): items.contains(.integer(m))
232 case .integer(let i): i == m
233 default: false
234 }
235 }
236 func base(_ m: Int, _ y: Int) throws -> Int { try day ?? (n > 0 ? 1 : lastDay(month: m, year: y)) }
237 let applies: Bool
238 if first.month == last.month {
239 let b = try base(first.month, first.year)
240 applies = monthMatches(first.month) && first.day <= b && b <= last.day
241 } else {
242 let firstBase = try base(first.month, first.year)
243 let lastBase = try base(last.month, last.year)
244 applies = (first.year < last.year || (first.year == last.year && first.month < last.month))
245 && ((monthMatches(first.month) && first.day <= firstBase) || (monthMatches(last.month) && lastBase <= last.day))
246 }
247 return applies ? Elisp.cons(optional(args, 4), try entry()) : .nil
248 }
249 lisp.define("diary-anniversary") { lisp, args in
250 try arity(args, 2...4, "diary-anniversary")
251 let made = try makeDate(lisp, args[0], args[1], optional(args, 2))
252 var dd = try bounded(made[1])
253 var mm = try bounded(made[0])
254 let y = try parts(try date()).year
255 let diff = Elisp.isNil(made[2]) ? 100 : y - (try bounded(made[2]))
256 if mm == 2, dd == 29, !isLeap(y) {
257 mm = 3
258 dd = 1
259 }
260 let d = try parts(try date())
261 guard diff > 0, (mm, dd, y) == (d.month, d.day, d.year) else { return .nil }
262 return Elisp.cons(optional(args, 3), .string(try Elisp.format([try entry(), .integer(diff), .string(try ordinalSuffix(diff))])))
263 }
264 lisp.define("diary-cyclic") { lisp, args in
265 try arity(args, 4...5, "diary-cyclic")
266 let n = try Elisp.int(args[0])
267 guard n > 0 else { throw Elisp.Signal(message: "Day count must be positive") }
268 let diff = try absolute(try date()) - (try absolute(.list(try makeDate(lisp, args[1], args[2], args[3]))))
269 let cycle = diff / n
270 guard diff >= 0, diff % n == 0 else { return .nil }
271 return Elisp.cons(optional(args, 4), .string(try Elisp.format([try entry(), .integer(cycle), .string(try ordinalSuffix(cycle))])))
272 }
273 lisp.define("diary-remind") { lisp, args in
274 try arity(args, 2...3, "diary-remind")
275 var days = args[1]
276 if case .integer(let n) = days, n < 0 {
277 guard n >= -Elisp.lengthLimit else { throw Elisp.Signal(message: "Too many days for diary-remind") }
278 days = Elisp.list((1...(-n)).map { .integer($0) })
279 }
280 func remind(_ days: Sexp) throws -> Sexp {
281 let applies = try lisp.eval(args[0])
282 if !Elisp.isNil(applies) { return applies }
283 if case .integer(let n) = days {
284 let shifted = gregorian(try absolute(try date()) + (try bounded(.integer(n))))
285 var found = try lisp.binding(["date": shifted]) { try lisp.eval(args[0]) }
286 guard !Elisp.isNil(found) else { return .nil }
287 if case .dotted = found { found = try Elisp.cdr(found) } else if case .list = found { found = try Elisp.cdr(found) }
288 let span = n % 7 == 0 ? String(format: "%d week%@", n / 7, n == 7 ? "" : "s") : String(format: "%d day%@", n, n == 1 ? "" : "s")
289 return .string("Reminder: Only " + span + " until " + Elisp.printed(found))
290 }
291 guard case .list(let items) = days, let first = items.first else { return .nil }
292 let head = try remind(first)
293 return Elisp.isNil(head) ? try remind(Elisp.list(Array(items.dropFirst()))) : head
294 }
295 return try remind(days)
296 }
297
298 lisp.define("org-anniversary") { lisp, args in try iso(lisp) { try lisp.callNamed("diary-anniversary", args) } }
299 lisp.define("org-cyclic") { lisp, args in try iso(lisp) { try lisp.callNamed("diary-cyclic", args) } }
300 lisp.define("org-block") { lisp, args in try iso(lisp) { try lisp.callNamed("diary-block", args) } }
301 lisp.define("org-date") { lisp, args in try iso(lisp) { try lisp.callNamed("diary-date", args) } }
302 lisp.define("calendar-check-holidays") { _, args in
303 try arity(args, 1...1, "calendar-check-holidays")
304 return Elisp.list(holidays(try absolute(args[0])).map(Sexp.string))
305 }
306 lisp.define("org-calendar-holiday") { _, _ in
307 let names = holidays(try absolute(try date()))
308 return names.isEmpty ? .nil : .string(names.joined(separator: "; "))
309 }
310 lisp.define("org-class") { _, args in
311 try arity(args, 7...Int.max, "org-class")
312 let ints = try args.prefix(7).map(bounded)
313 let first = Days.absolute(year: ints[0], month: ints[1], day: ints[2])
314 let last = Days.absolute(year: ints[3], month: ints[4], day: ints[5])
315 let d = try absolute(try date())
316 let skip = Array(args.dropFirst(7))
317 let week = Days.isoWeek(d)
318 guard first <= d, d <= last, Days.weekday(d) == ints[6], !skip.contains(.integer(week)) else { return .nil }
319 // `holidays' skips every holiday, a holiday's name that one.
320 let names = skip.isEmpty ? [] : holidays(d)
321 if !names.isEmpty, skip.contains(.symbol("holidays")) || names.contains(where: { skip.contains(.string($0)) }) { return .nil }
322 return try entry()
323 }
324 }
325}