Sources/OrgCore/Config/ElispTime.swift
228 lines · 12168 bytes
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 /// `encode-time` of a local date and time.
79 static func encode(_ parts: [Int], calendar: Calendar) throws -> Time {
80 guard let date = calendar.date(from: DateComponents(year: parts[0], month: parts[1], day: parts[2], hour: parts[3], minute: parts[4], second: parts.count > 5 ? parts[5] : 0)) else {
81 throw Unsupported(what: "date \(parts)")
82 }
83 return Time(seconds: Int(date.timeIntervalSince1970.rounded(.down)))
84 }
85
86 /// `date-to-time` for ISO 8601 dates, with or without a time.
87 static func dateToTime(_ s: String, calendar: Calendar) throws -> Time {
88 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 {
89 throw Unsupported(what: "date-to-time of \(s)")
90 }
91 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]
92 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)") }
93 return try encode(parts, calendar: calendar)
94 }
95
96 static func days(_ seconds: Int, calendar: Calendar) -> Int {
97 Days.absolute(Date(timeIntervalSince1970: Double(seconds)), calendar: calendar)
98 }
99
100 /// `format-time-string` with the conversions that don't depend on the locale, without
101 /// flags or widths.
102 static func formatTime(_ format: String, _ seconds: Int, calendar: Calendar) throws -> String {
103 let c = calendar.dateComponents([.year, .month, .day, .weekday, .hour, .minute, .second], from: Date(timeIntervalSince1970: Double(seconds)))
104 let (year, month, day, hour, minute, second) = (c.year!, c.month!, c.day!, c.hour!, c.minute!, c.second!)
105 let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
106 let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
107 let weekday = c.weekday! - 1
108 let hour12 = hour % 12 == 0 ? 12 : hour % 12
109 var out = ""
110 var chars = format.makeIterator()
111 while let ch = chars.next() {
112 guard ch == "%" else {
113 out.append(ch)
114 continue
115 }
116 guard let f = chars.next() else { throw Unsupported(what: "format-time-string %") }
117 switch f {
118 case "Y": out += String(year)
119 case "y": out += String(format: "%02d", year % 100)
120 case "m": out += String(format: "%02d", month)
121 case "d": out += String(format: "%02d", day)
122 case "e": out += String(format: "%2d", day)
123 case "H": out += String(format: "%02d", hour)
124 case "k": out += String(format: "%2d", hour)
125 case "I": out += String(format: "%02d", hour12)
126 case "l": out += String(format: "%2d", hour12)
127 case "M": out += String(format: "%02d", minute)
128 case "S": out += String(format: "%02d", second)
129 case "p": out += hour < 12 ? "AM" : "PM"
130 case "a": out += String(days[weekday].prefix(3))
131 case "A": out += days[weekday]
132 case "b", "h": out += String(months[month - 1].prefix(3))
133 case "B": out += months[month - 1]
134 case "u": out += String(weekday == 0 ? 7 : weekday)
135 case "w": out += String(weekday)
136 case "j": out += String(format: "%03d", Days.absolute(year: year, month: month, day: day) - Days.absolute(year: year, month: 1, day: 0))
137 case "F": out += String(format: "%d-%02d-%02d", year, month, day)
138 case "D": out += String(format: "%02d/%02d/%02d", month, day, year % 100)
139 case "R": out += String(format: "%02d:%02d", hour, minute)
140 case "T": out += String(format: "%02d:%02d:%02d", hour, minute, second)
141 case "s": out += String(seconds)
142 case "z":
143 let offset = calendar.timeZone.secondsFromGMT(for: Date(timeIntervalSince1970: Double(seconds))) / 60
144 out += String(format: "%@%02d%02d", offset < 0 ? "-" : "+", abs(offset) / 60, abs(offset) % 60)
145 case "n": out += "\n"
146 case "t": out += "\t"
147 case "%": out += "%"
148 default: throw Unsupported(what: "format-time-string %\(f)")
149 }
150 }
151 return out
152 }
153
154 /// Defines the time functions and the calendar functions diary sexps use, with times in
155 /// `calendar`'s time zone and `now` as the clock.
156 public func standardTime(now: @escaping () -> Date = Date.init, calendar: Calendar = .current) {
157 var calendar = calendar
158 if calendar.identifier != .gregorian {
159 var gregorian = Calendar(identifier: .gregorian)
160 gregorian.timeZone = calendar.timeZone
161 calendar = gregorian
162 }
163 let local = calendar
164 DiarySexp.defineCalendar(self)
165 define("current-time") { _, args in
166 try Elisp.arity(args, 0...0, "current-time")
167 return Time(now()).sexp
168 }
169 define("format-time-string") { _, args in
170 try Elisp.arity(args, 1...3, "format-time-string")
171 var zoned = local
172 if args.count > 2, !Elisp.isNil(args[2]) {
173 guard args[2] == Elisp.t || args[2] == .string("UTC") || args[2] == .integer(0) else { throw Unsupported(what: "format-time-string zone \(args[2].description)") }
174 zoned.timeZone = TimeZone(identifier: "UTC")!
175 }
176 return .string(try Elisp.formatTime(try Elisp.string(args[0]), try Elisp.wholeSeconds(args.count > 1 ? args[1] : .nil, now: now()), calendar: zoned))
177 }
178 define("org-time-string-to-time") { _, args in
179 try Elisp.arity(args, 1...1, "org-time-string-to-time")
180 return try Elisp.encode(try Elisp.orgTime(try Elisp.string(args[0])), calendar: local).pair
181 }
182 define("org-time-string-to-absolute") { _, args in
183 try Elisp.arity(args, 1...5, "org-time-string-to-absolute")
184 guard args.count == 1 else { throw Unsupported(what: "org-time-string-to-absolute with a day") }
185 let parts = try Elisp.orgTime(try Elisp.string(args[0]))
186 return .integer(Days.absolute(year: parts[0], month: parts[1], day: parts[2]))
187 }
188 for name in ["time-add", "time-subtract"] {
189 define(name) { _, args in
190 try Elisp.arity(args, 2...2, name)
191 let a = try Elisp.time(args[0], now: now())
192 let b = try Elisp.time(args[1], now: now())
193 let sign = name == "time-add" ? 1 : -1
194 var picoseconds = a.picoseconds + sign * b.picoseconds
195 var seconds = a.seconds + sign * b.seconds
196 if picoseconds < 0 {
197 picoseconds += Time.pico
198 seconds -= 1
199 } else if picoseconds >= Time.pico {
200 picoseconds -= Time.pico
201 seconds += 1
202 }
203 return Time(seconds: seconds, picoseconds: picoseconds, hz: max(a.hz, b.hz)).sexp
204 }
205 }
206 define("float-time") { _, args in
207 try Elisp.arity(args, 0...1, "float-time")
208 if case .float(let d)? = args.first { return .float(d) }
209 let time = try Elisp.time(args.first ?? .nil, now: now())
210 guard time.picoseconds % 1_000_000 == 0 else { throw Unsupported(what: "float-time of picoseconds") }
211 return .float(Double(time.seconds * 1_000_000 + time.picoseconds / 1_000_000) / 1_000_000)
212 }
213 define("date-to-time") { _, args in
214 try Elisp.arity(args, 1...1, "date-to-time")
215 return try Elisp.dateToTime(try Elisp.string(args[0]), calendar: local).pair
216 }
217 define("time-to-days") { _, args in
218 try Elisp.arity(args, 1...1, "time-to-days")
219 return .integer(Elisp.days(try Elisp.wholeSeconds(args[0], now: now()), calendar: local))
220 }
221 define("days-between") { _, args in
222 try Elisp.arity(args, 2...2, "days-between")
223 let a = try Elisp.dateToTime(try Elisp.string(args[0]), calendar: local)
224 let b = try Elisp.dateToTime(try Elisp.string(args[1]), calendar: local)
225 return .integer(Elisp.days(a.seconds, calendar: local) - Elisp.days(b.seconds, calendar: local))
226 }
227 }
228}