Sources/OrgCore/Config/ElispTime.swift
251 lines · 13558 bytes
12 symbols in this file
1import Foundation
2
3// Lisp timestamps, `format-time-string`, the Org and `time-*` functions, and the calendar
4// functions, for table formulas, Emacs Lisp blocks and capture templates.
5
6extension Elisp {
7 /// A Lisp timestamp: whole seconds, picoseconds past them, and the resolution it came
8 /// with (1 for an integer or `(HIGH LOW)`, else a list with microseconds).
9 struct Time {
10 var seconds: Int
11 var picoseconds = 0
12 var hz = 1
13
14 static let pico = 1_000_000_000_000
15
16 init(seconds: Int, picoseconds: Int = 0, hz: Int = 1) {
17 self.seconds = seconds
18 self.picoseconds = picoseconds
19 self.hz = hz
20 }
21
22 init(_ date: Date) {
23 let whole = date.timeIntervalSince1970.rounded(.down)
24 seconds = Int(whole)
25 picoseconds = Int((date.timeIntervalSince1970 - whole) * 1_000_000) * 1_000_000
26 hz = Self.pico
27 }
28
29 /// `(HIGH LOW USEC PSEC)`, or an integer when the resolution is seconds.
30 var sexp: Sexp {
31 hz == 1 ? .integer(seconds) : .list([.integer(seconds >> 16), .integer(seconds & 0xFFFF), .integer(picoseconds / 1_000_000), .integer(picoseconds % 1_000_000)])
32 }
33
34 /// `(HIGH LOW)`, as `encode-time` gives.
35 var pair: Sexp { .list([.integer(seconds >> 16), .integer(seconds & 0xFFFF)]) }
36 }
37
38 static func time(_ v: Sexp, now: Date) throws -> Time {
39 switch v {
40 case _ where isNil(v): return Time(now)
41 case .integer(let i): return Time(seconds: i)
42 case .float: throw Unsupported(what: "float times")
43 case .list(let parts) where (2...4).contains(parts.count):
44 let ints = try parts.map(int)
45 guard (-(1 << 40)...(1 << 40)).contains(ints[0]), (0..<65536).contains(ints[1]),
46 ints.dropFirst(2).allSatisfy({ (0..<1_000_000).contains($0) }) else { throw Unsupported(what: "time value \(v.description)") }
47 let micro = ints.count > 2 ? ints[2] : 0
48 let pico = ints.count > 3 ? ints[3] : 0
49 return Time(seconds: ints[0] << 16 + ints[1], picoseconds: micro * 1_000_000 + pico, hz: [1, 1, 1_000_000, Time.pico][ints.count - 1])
50 default: throw Unsupported(what: "time value \(v.description)")
51 }
52 }
53
54 /// The seconds of a time, floats included, for the functions that read only the date.
55 static func wholeSeconds(_ v: Sexp, now: Date) throws -> Int {
56 if case .float(let d) = v {
57 guard d.isFinite, abs(d) < 1e15 else { throw Unsupported(what: "time value \(v.description)") }
58 return Int(d.rounded(.down))
59 }
60 return try time(v, now: now).seconds
61 }
62
63 /// `org-ts-regexp0`.
64 static let orgTimeString = try! NSRegularExpression(pattern: "(([0-9]{4})-([0-9]{2})-([0-9]{2})( +[^\\]+0-9>\\r\\n \\-]+)?( +([0-9]{1,2}):([0-9]{2}))?)")
65
66 /// `org-parse-time-string`: year, month, day, hour and minute.
67 static func orgTime(_ s: String) throws -> [Int] {
68 let ns = s as NSString
69 guard let m = orgTimeString.firstMatch(in: s, range: NSRange(location: 0, length: ns.length)) else {
70 throw Signal(message: "Not an Org time string: \(s)")
71 }
72 func group(_ i: Int) -> Int { m.range(at: i).location == NSNotFound ? 0 : Int(ns.substring(with: m.range(at: i)))! }
73 let parts = [group(2), group(3), group(4), group(7), group(8)]
74 guard (1...12).contains(parts[1]), (1...31).contains(parts[2]), parts[3] < 24, parts[4] < 60 else { throw Unsupported(what: "time string \(s)") }
75 return parts
76 }
77
78 /// Days from 1 January 1970 to absolute day 1, 1 January of year 1.
79 static let epochDay = 719163
80
81 /// `encode-time` of a local date and time, in the proleptic Gregorian calendar as Emacs
82 /// counts. Foundation's Gregorian calendar is Julian before 15 October 1582, so earlier
83 /// dates are counted here, where no daylight saving time applies.
84 static func encode(_ parts: [Int], calendar: Calendar) throws -> Time {
85 let second = parts.count > 5 ? parts[5] : 0
86 if parts[0] >= 1583 {
87 guard let date = calendar.date(from: DateComponents(year: parts[0], month: parts[1], day: parts[2], hour: parts[3], minute: parts[4], second: second)) else {
88 throw Unsupported(what: "date \(parts)")
89 }
90 return Time(seconds: Int(date.timeIntervalSince1970.rounded(.down)))
91 }
92 let local = (Days.absolute(year: parts[0], month: parts[1], day: parts[2]) - epochDay) * 86400 + parts[3] * 3600 + parts[4] * 60 + second
93 func offset(_ seconds: Int) -> Int { calendar.timeZone.secondsFromGMT(for: Date(timeIntervalSince1970: Double(seconds))) }
94 return Time(seconds: local - offset(local - offset(local)))
95 }
96
97 /// The local date and time of `seconds` in the proleptic Gregorian calendar: the absolute
98 /// day, and the seconds into it.
99 static func civil(_ seconds: Int, calendar: Calendar) -> (day: Int, second: Int) {
100 let local = seconds + calendar.timeZone.secondsFromGMT(for: Date(timeIntervalSince1970: Double(seconds)))
101 let day = local >= 0 ? local / 86400 : -((-local - 1) / 86400) - 1
102 return (day + epochDay, local - day * 86400)
103 }
104
105 /// `date-to-time` for ISO 8601 dates, with or without a time.
106 static func dateToTime(_ s: String, calendar: Calendar) throws -> Time {
107 guard let m = s.wholeMatch(of: /([0-9]{4})-([0-9]{2})-([0-9]{2})(?:[ T]([0-9]{2}):([0-9]{2})(?::([0-9]{2}))?)?/) else {
108 throw Unsupported(what: "date-to-time of \(s)")
109 }
110 let parts = [Int(m.1)!, Int(m.2)!, Int(m.3)!, m.4.map { Int($0)! } ?? 0, m.5.map { Int($0)! } ?? 0, m.6.map { Int($0)! } ?? 0]
111 guard (1...12).contains(parts[1]), (1...31).contains(parts[2]), parts[3] < 24, parts[4] < 60, parts[5] < 60 else { throw Unsupported(what: "date-to-time of \(s)") }
112 return try encode(parts, calendar: calendar)
113 }
114
115 static func days(_ seconds: Int, calendar: Calendar) -> Int {
116 civil(seconds, calendar: calendar).day
117 }
118
119 /// `format-time-string` with the conversions that don't depend on the locale, without
120 /// flags or widths.
121 static func formatTime(_ format: String, _ seconds: Int, calendar: Calendar) throws -> String {
122 let (absolute, secondOfDay) = civil(seconds, calendar: calendar)
123 let (year, month, day) = Days.date(absolute)
124 let (hour, minute, second) = (secondOfDay / 3600, secondOfDay % 3600 / 60, secondOfDay % 60)
125 let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
126 let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
127 let weekday = Days.weekday(absolute)
128 // Four digits with the sign, and the last two digits of the year without it.
129 let yearText = year < 0 ? String(format: "-%03d", -year) : String(format: "%04d", year)
130 let shortYear = abs(year) % 100
131 let hour12 = hour % 12 == 0 ? 12 : hour % 12
132 var out = ""
133 var chars = format.makeIterator()
134 while let ch = chars.next() {
135 guard ch == "%" else {
136 out.append(ch)
137 continue
138 }
139 guard let f = chars.next() else { throw Unsupported(what: "format-time-string %") }
140 switch f {
141 case "Y": out += yearText
142 case "y": out += String(format: "%02d", shortYear)
143 case "m": out += String(format: "%02d", month)
144 case "d": out += String(format: "%02d", day)
145 case "e": out += String(format: "%2d", day)
146 case "H": out += String(format: "%02d", hour)
147 case "k": out += String(format: "%2d", hour)
148 case "I": out += String(format: "%02d", hour12)
149 case "l": out += String(format: "%2d", hour12)
150 case "M": out += String(format: "%02d", minute)
151 case "S": out += String(format: "%02d", second)
152 case "p": out += hour < 12 ? "AM" : "PM"
153 case "a": out += String(days[weekday].prefix(3))
154 case "A": out += days[weekday]
155 case "b", "h": out += String(months[month - 1].prefix(3))
156 case "B": out += months[month - 1]
157 case "u": out += String(weekday == 0 ? 7 : weekday)
158 case "w": out += String(weekday)
159 case "j": out += String(format: "%03d", Days.absolute(year: year, month: month, day: day) - Days.absolute(year: year, month: 1, day: 0))
160 case "F": out += (year > 9999 ? "+" : "") + yearText + String(format: "-%02d-%02d", month, day)
161 case "D": out += String(format: "%02d/%02d/%02d", month, day, shortYear)
162 case "R": out += String(format: "%02d:%02d", hour, minute)
163 case "T": out += String(format: "%02d:%02d:%02d", hour, minute, second)
164 case "s": out += String(seconds)
165 case "z":
166 let offset = calendar.timeZone.secondsFromGMT(for: Date(timeIntervalSince1970: Double(seconds))) / 60
167 out += String(format: "%@%02d%02d", offset < 0 ? "-" : "+", abs(offset) / 60, abs(offset) % 60)
168 case "n": out += "\n"
169 case "t": out += "\t"
170 case "%": out += "%"
171 default: throw Unsupported(what: "format-time-string %\(f)")
172 }
173 }
174 return out
175 }
176
177 /// Defines the time functions and the calendar functions diary sexps use, with times in
178 /// `calendar`'s time zone and `now` as the clock.
179 public func standardTime(now: @escaping () -> Date = Date.init, calendar: Calendar = .current) {
180 var calendar = calendar
181 if calendar.identifier != .gregorian {
182 var gregorian = Calendar(identifier: .gregorian)
183 gregorian.timeZone = calendar.timeZone
184 calendar = gregorian
185 }
186 let local = calendar
187 DiarySexp.defineCalendar(self)
188 define("current-time") { _, args in
189 try Elisp.arity(args, 0...0, "current-time")
190 return Time(now()).sexp
191 }
192 define("format-time-string") { _, args in
193 try Elisp.arity(args, 1...3, "format-time-string")
194 var zoned = local
195 if args.count > 2, !Elisp.isNil(args[2]) {
196 guard args[2] == Elisp.t || args[2] == .string("UTC") || args[2] == .integer(0) else { throw Unsupported(what: "format-time-string zone \(args[2].description)") }
197 zoned.timeZone = TimeZone(identifier: "UTC")!
198 }
199 return .string(try Elisp.formatTime(try Elisp.string(args[0]), try Elisp.wholeSeconds(args.count > 1 ? args[1] : .nil, now: now()), calendar: zoned))
200 }
201 define("org-time-string-to-time") { _, args in
202 try Elisp.arity(args, 1...1, "org-time-string-to-time")
203 return try Elisp.encode(try Elisp.orgTime(try Elisp.string(args[0])), calendar: local).pair
204 }
205 define("org-time-string-to-absolute") { _, args in
206 try Elisp.arity(args, 1...5, "org-time-string-to-absolute")
207 guard args.count == 1 else { throw Unsupported(what: "org-time-string-to-absolute with a day") }
208 let parts = try Elisp.orgTime(try Elisp.string(args[0]))
209 return .integer(Days.absolute(year: parts[0], month: parts[1], day: parts[2]))
210 }
211 for name in ["time-add", "time-subtract"] {
212 define(name) { _, args in
213 try Elisp.arity(args, 2...2, name)
214 let a = try Elisp.time(args[0], now: now())
215 let b = try Elisp.time(args[1], now: now())
216 let sign = name == "time-add" ? 1 : -1
217 var picoseconds = a.picoseconds + sign * b.picoseconds
218 var seconds = a.seconds + sign * b.seconds
219 if picoseconds < 0 {
220 picoseconds += Time.pico
221 seconds -= 1
222 } else if picoseconds >= Time.pico {
223 picoseconds -= Time.pico
224 seconds += 1
225 }
226 return Time(seconds: seconds, picoseconds: picoseconds, hz: max(a.hz, b.hz)).sexp
227 }
228 }
229 define("float-time") { _, args in
230 try Elisp.arity(args, 0...1, "float-time")
231 if case .float(let d)? = args.first { return .float(d) }
232 let time = try Elisp.time(args.first ?? .nil, now: now())
233 guard time.picoseconds % 1_000_000 == 0 else { throw Unsupported(what: "float-time of picoseconds") }
234 return .float(Double(time.seconds * 1_000_000 + time.picoseconds / 1_000_000) / 1_000_000)
235 }
236 define("date-to-time") { _, args in
237 try Elisp.arity(args, 1...1, "date-to-time")
238 return try Elisp.dateToTime(try Elisp.string(args[0]), calendar: local).pair
239 }
240 define("time-to-days") { _, args in
241 try Elisp.arity(args, 1...1, "time-to-days")
242 return .integer(Elisp.days(try Elisp.wholeSeconds(args[0], now: now()), calendar: local))
243 }
244 define("days-between") { _, args in
245 try Elisp.arity(args, 2...2, "days-between")
246 let a = try Elisp.dateToTime(try Elisp.string(args[0]), calendar: local)
247 let b = try Elisp.dateToTime(try Elisp.string(args[1]), calendar: local)
248 return .integer(Elisp.days(a.seconds, calendar: local) - Elisp.days(b.seconds, calendar: local))
249 }
250 }
251}