Calc dates !416

merged merged by cmc on 2026-11-20 22:48 UTC · krz/orgstar:parity-dates into main

7 files changed, +479 −26

Layout: unified · split

Sources/OrgApp/TableReason.swift +1
@@ -103,6 +103,7 @@ public enum TableReason {
103 case "constants that refer to themselves": return String(localized: "constants that refer to themselves", comment: comment) 103 case "constants that refer to themselves": return String(localized: "constants that refer to themselves", comment: comment)
104 case "date arithmetic": return String(localized: "date arithmetic", comment: comment) 104 case "date arithmetic": return String(localized: "date arithmetic", comment: comment)
105 case "date syntax": return String(localized: "date syntax", comment: comment) 105 case "date syntax": return String(localized: "date syntax", comment: comment)
106 case "daylight saving time": return String(localized: "daylight saving time", comment: comment)
106 case "division by zero": return String(localized: "division by zero", comment: comment) 107 case "division by zero": return String(localized: "division by zero", comment: comment)
107 case "duration size": return String(localized: "duration size", comment: comment) 108 case "duration size": return String(localized: "duration size", comment: comment)
108 case "empty vector": return String(localized: "empty vector", comment: comment) 109 case "empty vector": return String(localized: "empty vector", comment: comment)
Sources/OrgCore/Compute/Calc.swift +252 −19
@@ -42,6 +42,10 @@ public enum Calc {
42 public var degrees = true 42 public var degrees = true
43 /// `calc-prefer-frac`: dividing integers gives a fraction. 43 /// `calc-prefer-frac`: dividing integers gives a fraction.
44 public var preferFractions = false 44 public var preferFractions = false
45 /// The clock `now()` reads; nil is the system clock.
46 public var now: Date?
47 /// The local time zone, for `now()`, `julian` and `unixtime`.
48 public var timeZone = TimeZone.current
45 public init() {} 49 public init() {}
46 } 50 }
47 51
@@ -56,7 +60,7 @@ public enum Calc {
56 let value = try Evaluator(modes: modes).eval(tree) 60 let value = try Evaluator(modes: modes).eval(tree)
57 if numeric { 61 if numeric {
58 switch value { 62 switch value {
59 case .int, .float: break 63 case .int, .float, .frac: break
60 default: throw Failure("Number expected") 64 default: throw Failure("Number expected")
61 } 65 }
62 } 66 }
@@ -73,6 +77,7 @@ public enum Calc {
73 static func extra(_ n: Int, _ body: () throws -> Value) throws -> Value { 77 static func extra(_ n: Int, _ body: () throws -> Value) throws -> Value {
74 let v = try $precision.withValue(precision + n, operation: body) 78 let v = try $precision.withValue(precision + n, operation: body)
75 if case .float(let m, let e) = v { return try makeFloat(Int128(m), e) } 79 if case .float(let m, let e) = v { return try makeFloat(Int128(m), e) }
80 if case .date(.float(let m, let e)) = v { return .date(try makeFloat(Int128(m), e)) }
76 return v 81 return v
77 } 82 }
78 83
@@ -272,7 +277,8 @@ public enum Calc {
272 switch (a, b) { 277 switch (a, b) {
273 case (.nan, .vector), (.vector, .nan): throw Unsupported("vector arithmetic") 278 case (.nan, .vector), (.vector, .nan): throw Unsupported("vector arithmetic")
274 case (.nan, _), (_, .nan): return .nan 279 case (.nan, _), (_, .nan): return .nan
275 case (.date, .date): throw Unsupported("date arithmetic") 280 // Two dates add as their day numbers.
281 case (.date(let x), .date(let y)): return try add(x, y)
276 case (.date(let d), _): return .date(try add(d, b)) 282 case (.date(let d), _): return .date(try add(d, b))
277 case (_, .date(let d)): return .date(try add(a, d)) 283 case (_, .date(let d)): return .date(try add(a, d))
278 default: break 284 default: break
@@ -310,16 +316,14 @@ public enum Calc {
310 case .float(let m, let e): return .float(-m, e) 316 case .float(let m, let e): return .float(-m, e)
311 case .frac(let n, let d): return .frac(-n, d) 317 case .frac(let n, let d): return .frac(-n, d)
312 case .vector: throw Unsupported("vector arithmetic") 318 case .vector: throw Unsupported("vector arithmetic")
313 case .date: throw Unsupported("date arithmetic") 319 case .date(let d): return .date(try negate(d))
314 case .nan: return .nan 320 case .nan: return .nan
315 } 321 }
316 } 322 }
317 323
318 /// `a - b`: a date less a date is the days between them. 324 /// `a - b`: a date less a date is the days between them.
319 static func subtract(_ a: Value, _ b: Value) throws -> Value { 325 static func subtract(_ a: Value, _ b: Value) throws -> Value {
320 if case .date(let x) = a, case .date(let y) = b { return try add(x, try negate(y)) } 326 try add(a, try negate(b))
321 if case .date(let x) = a, b != .nan { return .date(try add(x, try negate(b))) }
322 return try add(a, try negate(b))
323 } 327 }
324 328
325 static func isNaN(_ a: Value, _ b: Value) -> Bool { 329 static func isNaN(_ a: Value, _ b: Value) -> Bool {
@@ -768,16 +772,13 @@ public enum Calc {
768 772
769 static let weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] 773 static let weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
770 774
771 /// `calc-date-format` as Org sets it: `YYYY-MM-DD Www`, then ` hh:mm` for a time of day. 775 /// `calc-date-format` as Org sets it: `YYYY-MM-DD Www`, then ` hh:mm` for a day number
776 /// that isn't an integer.
772 static func formatDate(_ value: Value) throws -> String { 777 static func formatDate(_ value: Value) throws -> String {
773 let days = try double(value) 778 let dt = try dateParts(value)
774 let day = Int(days.rounded(.down)) 779 let year = dt.year > 0 && dt.year < 100 ? "+\(dt.year)" : String(dt.year)
775 let date = Days.date(day) 780 var text = year + String(format: "-%02d-%02d ", dt.month, dt.day) + weekdays[Days.weekday(try floorInt(value))]
776 var text = String(format: "%04d-%02d-%02d ", date.year, date.month, date.day) + weekdays[Days.weekday(day)] 781 if let time = dt.time { text += String(format: " %02d:%02d", time.hour, time.minute) }
777 if case .float = value, days != Double(day) {
778 let seconds = Int(((days - Double(day)) * 86400).rounded())
779 text += String(format: " %02d:%02d", seconds / 3600, seconds / 60 % 60)
780 }
781 return text 782 return text
782 } 783 }
783 784
@@ -787,11 +788,108 @@ public enum Calc {
787 guard let m = text.firstMatch(of: /^([0-9]{4})-([0-9]{2})-([0-9]{2})(?: +[A-Za-z]+)?(?: +([0-9]{1,2}):([0-9]{2})(?::([0-9]{2}))?)?$/) else { 788 guard let m = text.firstMatch(of: /^([0-9]{4})-([0-9]{2})-([0-9]{2})(?: +[A-Za-z]+)?(?: +([0-9]{1,2}):([0-9]{2})(?::([0-9]{2}))?)?$/) else {
788 throw Unsupported("date syntax") 789 throw Unsupported("date syntax")
789 } 790 }
790 let day = Days.absolute(year: Int(m.1)!, month: Int(m.2)!, day: Int(m.3)!) 791 // `math-parse-date-validate`: a year under 100 is 19xx or 20xx.
792 var year = Int(m.1)!
793 if year < 100 { year += year < 40 ? 2000 : 1900 }
794 let day = Days.absolute(year: year, month: Int(m.2)!, day: Int(m.3)!)
791 guard let hour = m.4.flatMap({ Int($0) }), let minute = m.5.flatMap({ Int($0) }) else { return .date(.int(day)) } 795 guard let hour = m.4.flatMap({ Int($0) }), let minute = m.5.flatMap({ Int($0) }) else { return .date(.int(day)) }
792 let seconds = hour * 3600 + minute * 60 + (m.6.flatMap { Int($0) } ?? 0) 796 return try dateTime(day, hour * 3600 + minute * 60 + (m.6.flatMap { Int($0) } ?? 0))
793 if seconds == 0 { return .date(.int(day)) } 797 }
794 return .date(try add(.int(day), try divide(.int(seconds), .int(86400)))) 798
799 // MARK: - Dates
800
801 /// Calc numbers years without a year 0: -1 comes before 1.
802 static func astronomical(_ year: Int) -> Int { year > 0 ? year : year == 0 ? 0 : year + 1 }
803
804 /// `math-absolute-from-gregorian-dt`.
805 static func absolute(_ year: Int, _ month: Int, _ day: Int) throws -> Int {
806 guard abs(year) < 1_000_000_000 else { throw Unsupported("number size") }
807 return Days.absolute(year: astronomical(year), month: month, day: day)
808 }
809
810 /// `math-days-in-month`.
811 static func daysInMonth(_ year: Int, _ month: Int) throws -> Int {
812 try absolute(year, month + 1, 1) - absolute(year, month, 1)
813 }
814
815 /// `math-dt-to-date` with a time of day: a float day number.
816 static func dateTime(_ day: Int, _ seconds: Int) throws -> Value {
817 .date(try add(try float(.int(day)), try divide(.int(seconds), .float(864, 2))))
818 }
819
820 /// `math-dt-to-date`.
821 static func dateValue(_ year: Int, _ month: Int, _ day: Int, _ time: (hour: Int, minute: Int, second: Int)? = nil) throws -> Value {
822 guard (1...12).contains(month), (1...31).contains(day) else { throw Unsupported("arguments") }
823 let n = try absolute(year, month, day)
824 guard let time else { return .date(.int(n)) }
825 guard [time.hour, time.minute, time.second].allSatisfy({ abs($0) < 1_000_000 }) else { throw Unsupported("arguments") }
826 return try dateTime(n, time.hour * 3600 + time.minute * 60 + time.second)
827 }
828
829 /// The day number of a date form, or a real number, which Calc's date functions also take.
830 static func dayNumber(_ v: Value) throws -> Value {
831 let x: Value = if case .date(let d) = v { d } else { v }
832 _ = try sign(x)
833 return x
834 }
835
836 /// `math-date-to-dt`: the day, with the time of day when the day number isn't an integer.
837 static func dateParts(_ v: Value) throws -> (year: Int, month: Int, day: Int, time: (hour: Int, minute: Int, second: Int)?) {
838 let x = try dayNumber(v)
839 let day = try floorInt(x)
840 guard abs(day) < 100_000_000_000 else { throw Unsupported("number size") }
841 let date = Days.date(day)
842 let year = date.year > 0 ? date.year : date.year - 1
843 if case .int = x { return (year, date.month, date.day, nil) }
844 // Above 12 digits Calc keeps fractions of a second.
845 guard precision <= 12 else { throw Unsupported("calc precision") }
846 let seconds = try trunc(try round(try multiply(try subtract(x, .int(day)), .int(86400)), even: false))
847 return (year, date.month, date.day, (seconds / 3600, seconds / 60 % 60, seconds % 60))
848 }
849
850 /// `math-to-business-day`, with Calc's default holidays: Saturdays and Sundays.
851 static func toBusinessDay(_ v: Value) throws -> (Value, holiday: Bool) {
852 let x = try dayNumber(v)
853 let day = try floorInt(x)
854 try checkHolidayRange(day)
855 let weekday = Days.weekday(day)
856 let delta = day / 7 * 2 + (weekday > 0 ? 1 : 0)
857 return (try add(.int(day - delta), try subtract(x, .int(day))), weekday == 0 || weekday == 6)
858 }
859
860 /// `math-setup-holidays` with a date: Calc's holidays cover the years 1 to 2737.
861 static func checkHolidayRange(_ day: Int) throws {
862 guard (try absolute(1, 1, 1)...absolute(2737, 12, 31)).contains(day) else { throw Unsupported("arguments") }
863 }
864
865 /// `math-from-business-day`.
866 static func fromBusinessDay(_ n: Value) throws -> Value {
867 var day = try floorInt(n)
868 let time = try subtract(n, .int(day))
869 var left = ((day % 5) + 5) % 5
870 day += day / 5 * 2
871 var weekday = 0
872 while true {
873 if weekday == 0 || weekday == 6 {
874 day += 1
875 } else {
876 left -= 1
877 if left < 0 { break }
878 }
879 weekday += 1
880 }
881 try checkHolidayRange(day)
882 return .date(try add(.int(day), time))
883 }
884
885 /// `calcFunc-tzone` for the local zone, in seconds. Calc applies the current year's
886 /// daylight saving rules to every date, which isn't reproduced, so only zones without
887 /// daylight saving time are supported.
888 static func zoneOffset(_ zone: TimeZone) throws -> Int {
889 guard !zone.isDaylightSavingTime(), zone.nextDaylightSavingTimeTransition == nil else {
890 throw Unsupported("daylight saving time")
891 }
892 return -zone.secondsFromGMT()
795 } 893 }
796 894
797 // MARK: - Parsing 895 // MARK: - Parsing
@@ -856,6 +954,8 @@ public enum Calc {
856 954
857 mutating func comparison() throws -> Node { 955 mutating func comparison() throws -> Node {
858 let left = try sum() 956 let left = try sum()
957 // Calc reads `<<` and `>>` as one token, so `1<<2026-10-05 Mon>` is a syntax error.
958 if take("<<") || take(">>") { throw Unsupported("formula syntax") }
859 for (token, op) in [("==", "="), ("!=", "≠"), ("<=", "≤"), (">=", "≥"), ("<", "<"), (">", ">")] where take(token) { 959 for (token, op) in [("==", "="), ("!=", "≠"), ("<=", "≤"), (">=", "≥"), ("<", "<"), (">", ">")] where take(token) {
860 let right = try sum() 960 let right = try sum()
861 if let next = peek(), "=!<>".contains(next) { throw Unsupported("chained comparison") } 961 if let next = peek(), "=!<>".contains(next) { throw Unsupported("chained comparison") }
@@ -1199,6 +1299,20 @@ public enum Calc {
1199 return args[0] 1299 return args[0]
1200 } 1300 }
1201 1301
1302 /// An integer argument, from an integer or a float with an integer value
1303 /// (`math-messy-integerp`).
1304 func integer(_ v: Value) throws -> Int {
1305 guard isWhole(v) else { throw Unsupported("arguments") }
1306 return try trunc(v)
1307 }
1308
1309 /// The local date and time `now()` reads.
1310 func clock() -> DateComponents {
1311 var calendar = Calendar(identifier: .gregorian)
1312 calendar.timeZone = modes.timeZone
1313 return calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: modes.now ?? Date())
1314 }
1315
1202 func radians(_ x: Double) -> Double { modes.degrees ? x * .pi / 180 : x } 1316 func radians(_ x: Double) -> Double { modes.degrees ? x * .pi / 180 : x }
1203 func angle(_ x: Double) -> Double { modes.degrees ? x * 180 / .pi : x } 1317 func angle(_ x: Double) -> Double { modes.degrees ? x * 180 / .pi : x }
1204 1318
@@ -1229,6 +1343,8 @@ public enum Calc {
1229 case "vmedian": 1343 case "vmedian":
1230 var items = try elements(args) 1344 var items = try elements(args)
1231 guard !items.isEmpty else { throw Unsupported("empty vector") } 1345 guard !items.isEmpty else { throw Unsupported("empty vector") }
1346 // Calc leaves the median of dates unevaluated.
1347 if items.contains(where: { if case .date = $0 { true } else { false } }) { throw Unsupported("arguments") }
1232 try items.sort { try compare($0, $1) < 0 } 1348 try items.sort { try compare($0, $1) < 0 }
1233 if items.count % 2 == 1 { return items[items.count / 2] } 1349 if items.count % 2 == 1 { return items[items.count / 2] }
1234 return try divide(try add(items[items.count / 2 - 1], items[items.count / 2]), .int(2)) 1350 return try divide(try add(items[items.count / 2 - 1], items[items.count / 2]), .int(2))
@@ -1261,8 +1377,14 @@ public enum Calc {
1261 return best 1377 return best
1262 case "abs": 1378 case "abs":
1263 let x = try one(args) 1379 let x = try one(args)
1380 if case .date(let d) = x {
1381 // Calc leaves abs of day number 0 unevaluated.
1382 if d == .int(0) { throw Unsupported("date arithmetic") }
1383 return .date(try compare(d, .int(0)) < 0 ? try negate(d) : d)
1384 }
1264 return try compare(x, .int(0)) < 0 ? try negate(x) : x 1385 return try compare(x, .int(0)) < 0 ? try negate(x) : x
1265 case "floor", "ceil", "trunc": 1386 case "floor", "ceil", "trunc":
1387 if args.count == 1, case .date(let d) = args[0] { return .date(try call(name, [d])) }
1266 var x = try one(args) 1388 var x = try one(args)
1267 if case .frac(let n, let d) = x { x = try divide(.int(n), .int(d)) } 1389 if case .frac(let n, let d) = x { x = try divide(.int(n), .int(d)) }
1268 if case .int = x { return x } 1390 if case .int = x { return x }
@@ -1272,6 +1394,10 @@ public enum Calc {
1272 return .int(i) 1394 return .int(i)
1273 case "round": 1395 case "round":
1274 guard args.count == 1 || args.count == 2 else { throw Unsupported("arguments") } 1396 guard args.count == 1 || args.count == 2 else { throw Unsupported("arguments") }
1397 if case .date(let d) = args[0] {
1398 guard args.count == 1 else { throw Unsupported("arguments") }
1399 return .date(try call(name, [d]))
1400 }
1275 var x = args[0] 1401 var x = args[0]
1276 if case .frac(let n, let d) = x { x = try divide(.int(n), .int(d)) } 1402 if case .frac(let n, let d) = x { x = try divide(.int(n), .int(d)) }
1277 if args.count == 2 { 1403 if args.count == 2 {
@@ -1533,6 +1659,113 @@ public enum Calc {
1533 } 1659 }
1534 throw Unsupported("number") 1660 throw Unsupported("number")
1535 } 1661 }
1662 case "now":
1663 guard args.isEmpty else { throw Unsupported("arguments") }
1664 let c = clock()
1665 return try dateValue(c.year!, c.month!, c.day!, (c.hour!, c.minute!, c.second!))
1666 case "date":
1667 // `date(d)` converts between a date and its day number; otherwise the
1668 // arguments are [year,] month, day[, hour[, minute[, second]]].
1669 if args.count == 1 {
1670 if case .date(let d) = args[0] { return d }
1671 return .date(try dayNumber(args[0]))
1672 }
1673 guard (2...6).contains(args.count) else { throw Unsupported("arguments") }
1674 let n = try args.map(integer)
1675 if n.count == 2 { return try dateValue(clock().year!, n[0], n[1]) }
1676 return try dateValue(n[0], n[1], n[2], n.count > 3 ? (n[3], n.count > 4 ? n[4] : 0, n.count > 5 ? n[5] : 0) : nil)
1677 case "year", "month", "day", "hour", "minute", "second", "yearday":
1678 let dt = try dateParts(try one(args))
1679 switch name {
1680 case "year": return .int(dt.year)
1681 case "month": return .int(dt.month)
1682 case "day": return .int(dt.day)
1683 case "hour": return .int(dt.time?.hour ?? 0)
1684 case "minute": return .int(dt.time?.minute ?? 0)
1685 case "second": return .int(dt.time?.second ?? 0)
1686 default: return .int(try absolute(dt.year, dt.month, dt.day) - absolute(dt.year, 1, 1) + 1)
1687 }
1688 case "weekday":
1689 return .int(Days.weekday(try floorInt(try dayNumber(try one(args)))))
1690 case "newweek":
1691 guard (1...2).contains(args.count) else { throw Unsupported("arguments") }
1692 let day = try floorInt(try dayNumber(args[0]))
1693 let weekday = args.count > 1 ? try integer(args[1]) : 0
1694 guard (0...6).contains(weekday) else { throw Unsupported("arguments") }
1695 return .date(.int(day - Days.weekday(day - weekday)))
1696 case "newmonth":
1697 guard (1...2).contains(args.count) else { throw Unsupported("arguments") }
1698 var day = args.count > 1 ? try integer(args[1]) : 1
1699 guard (0...31).contains(day) else { throw Unsupported("arguments") }
1700 let dt = try dateParts(args[0])
1701 let days = try daysInMonth(dt.year, dt.month)
1702 day = day == 0 || day > days ? days - 1 : day - 1
1703 return .date(.int(try absolute(dt.year, dt.month, 1) + day))
1704 case "newyear":
1705 guard (1...2).contains(args.count) else { throw Unsupported("arguments") }
1706 var day = args.count > 1 ? try integer(args[1]) : 1
1707 let dt = try dateParts(args[0])
1708 if (-12 ... -1).contains(day) { return .date(.int(try absolute(dt.year, -day, 1))) }
1709 guard (0...366).contains(day) else { throw Unsupported("arguments") }
1710 let days = try daysInMonth(dt.year, 2) == 29 ? 366 : 365
1711 if day == 0 || day > days { day = days }
1712 return .date(.int(try absolute(dt.year, 1, 1) + day - 1))
1713 case "incmonth", "incyear":
1714 guard (1...2).contains(args.count) else { throw Unsupported("arguments") }
1715 let step = args.count > 1 ? args[1] : .int(1)
1716 let months = try integer(name == "incyear" ? try multiply(step, .int(12)) : step)
1717 guard abs(months) < 1_000_000_000 else { throw Unsupported("arguments") }
1718 let dt = try dateParts(args[0])
1719 let m = dt.month - 1 + months
1720 let extra = m >= 0 ? m / 12 : (m - 11) / 12
1721 let month = m - extra * 12 + 1
1722 var year = dt.year + extra
1723 let day = min(dt.day, try daysInMonth(year, month))
1724 // Past the year zero, which Calc doesn't have.
1725 if dt.year > 0, year <= 0 { year -= 1 }
1726 if dt.year < 0, year >= 0 { year += 1 }
1727 return try dateValue(year, month, day, dt.time)
1728 case "badd", "bsub":
1729 guard args.count == 2 else { throw Unsupported("arguments") }
1730 var (a, b) = (args[0], args[1])
1731 if name == "bsub" {
1732 guard case .date = a else { throw Unsupported("arguments") }
1733 if case .date = b {
1734 if try compare(a, b) < 0 { return try negate(try call(name, [b, a])) }
1735 let (x, xHoliday) = try toBusinessDay(a)
1736 let (y, yHoliday) = try toBusinessDay(b)
1737 return try add(try subtract(x, y), .int(yHoliday && !xHoliday ? 1 : 0))
1738 }
1739 b = try negate(b)
1740 }
1741 if case .date = b {
1742 if case .date = a { throw Unsupported("arguments") }
1743 (a, b) = (b, a)
1744 }
1745 guard case .date = a else { throw Unsupported("arguments") }
1746 if try sign(b) == 0 { return a }
1747 let (day, holiday) = try toBusinessDay(a)
1748 return try fromBusinessDay(try add(day, holiday && sign(b) > 0 ? try subtract(b, .int(1)) : b))
1749 case "julian":
1750 // `math-julian-date-beginning`: 1721424.5 days before day 0.
1751 let x = try one(args)
1752 if case .date(let d) = x {
1753 if case .int = d { return try add(d, .int(1721425)) }
1754 return try add(d, try add(.float(17214245, -1), try divide(.int(try zoneOffset(modes.timeZone)), .float(864, 2))))
1755 }
1756 if case .int(let d) = x { return .date(try add(.int(d), .int(-1721425))) }
1757 let shifted = try subtract(try dayNumber(x), .float(17214245, -1))
1758 return .date(try subtract(shifted, try divide(.int(try zoneOffset(modes.timeZone)), .float(864, 2))))
1759 case "unixtime":
1760 // `math-unix-epoch`: day 719163.
1761 let x = try one(args)
1762 if case .date(let d) = x {
1763 guard precision <= 12 else { throw Unsupported("calc precision") }
1764 let seconds = try round(try multiply(try subtract(d, .int(719163)), .int(86400)), even: false)
1765 return try add(seconds, .int(try zoneOffset(modes.timeZone)))
1766 }
1767 let day = try add(.int(719163), try divide(try dayNumber(x), .float(864, 2)))
1768 return .date(try subtract(day, try divide(.int(try zoneOffset(modes.timeZone)), .float(864, 2))))
1536 default: 1769 default:
1537 throw Unsupported("function \(name)") 1770 throw Unsupported("function \(name)")
1538 } 1771 }
Sources/OrgCore/Compute/TableFormulas.swift +3 −1
@@ -632,7 +632,9 @@ extension EmacsBuffer {
632 } else { 632 } else {
633 do { 633 do {
634 result = try Calc.evaluate(form, modes: modes, numeric: !mode.keepEmpty && mode.numbers) 634 result = try Calc.evaluate(form, modes: modes, numeric: !mode.keepEmpty && mode.numbers)
635 } catch is Calc.Failure { 635 } catch let failure as Calc.Failure {
636 // A duration formula takes Calc's error for a string, as org does.
637 if duration != nil { throw UserError(message: "Wrong type argument: stringp, (0 \"\(failure.reason)\")") }
636 (result, fmt) = ("#ERROR", nil) 638 (result, fmt) = ("#ERROR", nil)
637 } 639 }
638 } 640 }
Tests/OrgCoreTests/CalcTests.swift +128 −6
@@ -4,7 +4,7 @@ import Testing
4 4
5/// Runs `calc-eval` with org's table modes over a list of expressions. 5/// Runs `calc-eval` with org's table modes over a list of expressions.
6enum CalcOracle { 6enum CalcOracle {
7 static func run(_ cases: [(expression: String, format: String)], precision: Int = 12) throws -> [String] { 7 static func run(_ cases: [(expression: String, format: String)], precision: Int = 12, zone: String = "UTC") throws -> [String] {
8 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-calc-\(UUID().uuidString)") 8 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-calc-\(UUID().uuidString)")
9 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) 9 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
10 defer { try? FileManager.default.removeItem(at: folder) } 10 defer { try? FileManager.default.removeItem(at: folder) }
@@ -33,7 +33,7 @@ enum CalcOracle {
33 (with-temp-file (getenv "ORACLE_OUTPUT") 33 (with-temp-file (getenv "ORACLE_OUTPUT")
34 (insert (json-encode (vconcat results))))) 34 (insert (json-encode (vconcat results)))))
35 """#.write(to: script, atomically: true, encoding: .utf8) 35 """#.write(to: script, atomically: true, encoding: .utf8)
36 _ = try EmacsOracle.run(["-Q", "--batch", "-l", script.path], environment: ["ORACLE_INPUT": input.path, "ORACLE_OUTPUT": output.path, "ORACLE_PREC": String(precision)]) 36 _ = try EmacsOracle.run(["-Q", "--batch", "-l", script.path], environment: ["ORACLE_INPUT": input.path, "ORACLE_OUTPUT": output.path, "ORACLE_PREC": String(precision), "TZ": zone])
37 return try JSONDecoder().decode([String].self, from: Data(contentsOf: output)) 37 return try JSONDecoder().decode([String].self, from: Data(contentsOf: output))
38 } 38 }
39} 39}
@@ -64,8 +64,105 @@ struct CalcTests {
64 "if(1.5, 2.5, 3)", "7%3", "-7%3", "7%-3", "7.5%2", "7\\2", "-7\\2", "7.5\\2", "mod(10,4)", "idiv(-9,4)", "fact(5)", "fact(0)", 64 "if(1.5, 2.5, 3)", "7%3", "-7%3", "7%-3", "7.5%2", "7\\2", "-7\\2", "7.5\\2", "mod(10,4)", "idiv(-9,4)", "fact(5)", "fact(0)",
65 "vsdev([1,2,3,4])", "vvar([1,2,3])", "vpvar([1,2,3,4])", "vpsdev([2,4,4,4,5,5,7,9])", "vsdev([1.5,2.5,4])", 65 "vsdev([1,2,3,4])", "vvar([1,2,3])", "vpvar([1,2,3,4])", "vpsdev([2,4,4,4,5,5,7,9])", "vsdev([1.5,2.5,4])",
66 "2+3<4*2", "1<2 && 3<4", "!(1<2)", "(1<2)+(2<3)", 66 "2+3<4*2", "1<2 && 3<4", "!(1<2)", "(1<2)+(2<3)",
67 // Date forms and date functions.
68 "<2026-10-05 Mon 00:00>", "<2026-10-05 Mon 00:00>+1", "<2026-10-05 Mon 12:00>+0.5", "<2026-10-05 Mon>+1e-9",
69 "<2026-10-05 Mon>+0.1", "<2026-10-05 Mon>+1:2", "<2026-10-05 Mon 10:00>-1:3", "<2026-10-05 Mon 23:59:59>+0",
70 "<2026-10-05 Mon>+<2026-10-06 Tue>", "1+<2026-10-05 Mon>+<2026-10-06 Tue>", "<2026-10-05 Mon>+1-<2026-10-01 Thu>",
71 "-(<2026-10-05 Mon>)+<2026-10-01 Thu>", "0-<2026-10-05 Mon>", "-<2026-10-05 Mon>", "<2026-10-05 Mon>-nan",
72 "<2026-10-05 Mon>-<2026-10-04 Sun 12:00>", "<2026-10-05 Mon> == <2026-10-05 Mon 00:00>",
73 "vsum([<2026-10-05 Mon>,1.5])", "vsum([<2026-10-05 Mon 06:00>,0.1])", "vsum([<2026-10-05 Mon>,<2026-10-06 Tue>])",
74 "vsum([<2026-10-05 Mon>,<2026-10-06 Tue>,<2026-10-10 Sat>])", "vmean([<2026-10-05 Mon>,<2026-10-06 Tue>])",
75 "vmean([<2026-10-05 Mon 06:00>,<2026-10-05 Mon 12:00>])", "vmin([<2026-10-05 Mon>,<2026-10-07 Wed>])",
76 "vmax([<2026-10-05 Mon>],[<2026-10-06 Tue>])", "vmin([<2026-10-05 Mon 00:00>,<2026-10-05 Mon>])",
77 "vcount([<2026-10-05 Mon>])", "max(<2026-10-05 Mon>,<2026-10-06 Tue>)", "abs(<2026-10-05 Mon>)",
78 "floor(<2026-10-05 Mon 10:30>)", "ceil(<2026-10-05 Mon 13:00>)", "trunc(<2026-10-05 Mon 13:00>)",
79 "round(<2026-10-05 Mon 13:00>)", "round(<2026-10-05 Mon 11:00>)", "floor(<2026-10-05 Mon>)",
80 "year(<2026-10-05 Mon>)", "month(<2026-10-05 Mon 10:30>)", "day(<2026-10-05 Mon>)", "weekday(<2026-10-05 Mon>)",
81 "weekday(<2026-10-05 Mon 10:00>)", "weekday(-1)", "weekday(5)", "hour(<2026-10-05 Mon 10:30>)",
82 "minute(<2026-10-05 Mon 10:30>)", "second(<2026-10-05 Mon 10:30:45>)", "hour(<2026-10-05 Mon>)",
83 "yearday(<2026-10-05 Mon>)", "yearday(<2024-12-31 Tue>)", "year(5)", "year(<2026-10-05 Mon>)+1",
84 "date(2026,10,5)", "date(2026,10,5,10,30,0)", "date(2026,1,1,10)", "date(2026,1,1,10,30)", "date(2026,1,1,25,0,0)",
85 "date(2026,1,1,10,70,0)", "date(2026,2,31)", "date(2026.,2.,3.)", "date(2026,10,5,0,0,0)", "date(10,5)",
86 "date(<2026-10-05 Mon>)", "date(<2026-10-05 Mon 06:00>)", "date(<2026-10-05 Mon>)+1", "date(739000)",
87 "date(739000.5)", "date(739000.)", "date(1:2)", "date(5)", "date(36524)", "date(36890)", "date(365250)",
88 "date(-5)", "date(-400)", "date(0)", "date(-366)", "date(-367)",
89 "incmonth(<2026-01-31 Sat>,1)", "incmonth(<2026-10-05 Mon 10:30>,-14)", "incmonth(<2026-10-05 Mon>)",
90 "incmonth(<2026-10-05 Mon>,2.)", "incmonth(5,1)", "incmonth(<2024-02-29 Thu>,12)", "incmonth(<2026-03-31 Tue>,-1)",
91 "incmonth(<2026-12-15 Tue>,1)", "incmonth(<2026-01-15 Thu>,-1)", "incmonth(<2026-01-15 Thu>,-25)",
92 "incmonth(400,-24)", "incmonth(-400,24)", "incyear(<2024-02-29 Thu>,1)", "incyear(<2024-02-29 Thu>,4)",
93 "incyear(<2026-10-05 Mon>)", "incyear(<2026-10-05 Mon>,1.5)", "incyear(<2026-10-05 Mon 08:00>,-3)",
94 "newmonth(<2026-10-15 Thu>)", "newmonth(<2026-02-15 Sun>,31)", "newmonth(<2026-02-15 Sun>,0)",
95 "newmonth(<2026-02-15 Sun 10:00>,5)", "newmonth(<2024-02-15 Thu>,30)", "newmonth(<2026-10-15 Thu>,31)",
96 "newyear(<2026-10-15 Thu>)", "newyear(<2026-10-15 Thu>,0)", "newyear(<2026-10-15 Thu>,-3)",
97 "newyear(<2026-10-15 Thu 10:00>,40)", "newyear(<2024-10-15 Tue>,366)", "newyear(<2026-10-15 Thu>,366)",
98 "newyear(<2026-10-15 Thu>,-12)", "newweek(<2026-10-15 Thu>)", "newweek(<2026-10-15 Thu>,3)",
99 "newweek(<2026-10-15 Thu 10:00>)", "newweek(<2026-10-11 Sun>,1)", "newweek(<2026-10-17 Sat>,6)",
100 "badd(<2026-10-09 Fri>,1)", "badd(<2026-10-10 Sat>,1)", "badd(<2026-10-10 Sat>,-1)", "badd(<2026-10-10 Sat>,0)",
101 "badd(<2026-10-09 Fri 10:00>,2.5)", "badd(1,<2026-10-09 Fri>)", "badd(<2026-10-05 Mon>,10)", "badd(<2026-10-05 Mon>,-10)",
102 "badd(<2026-10-11 Sun>,1)", "badd(<2026-10-11 Sun>,-1)", "badd(<2026-10-05 Mon>,0.5)", "badd(<2026-10-05 Mon>,-0.5)",
103 "bsub(<2026-10-12 Mon>,1)", "bsub(<2026-10-12 Mon>,<2026-10-09 Fri>)", "bsub(<2026-10-11 Sun>,<2026-10-09 Fri>)",
104 "bsub(<2026-10-12 Mon>,<2026-10-10 Sat>)", "bsub(<2026-10-05 Mon>,<2026-10-12 Mon>)",
105 "bsub(<2026-10-12 Mon 12:00>,<2026-10-09 Fri 06:00>)", "bsub(<2026-12-31 Thu>,<2026-01-01 Thu>)",
106 "bsub(<2026-10-10 Sat>,<2026-10-11 Sun>)", "bsub(<2026-10-11 Sun>,<2026-10-10 Sat>)",
107 "julian(<2026-10-05 Mon>)", "julian(<2026-10-05 Mon 12:00>)", "julian(2461319)", "julian(2461319.5)", "julian(1:2)",
108 "unixtime(<2026-10-05 Mon>)", "unixtime(<2026-10-05 Mon 10:30>)", "unixtime(1791158400)", "unixtime(1.5)",
109 "unixtime(0)", "unixtime(-86400)", "unixtime(<1970-01-01 Thu>)",
110 "abs(-<2026-10-05 Mon>)", "abs(date(-1,1,1))", "abs(-<2026-10-05 Mon 06:00>)", "abs(date(1,1,1))",
111 "abs(date(1,1,1)-1.5)", "abs(date(1,1,1)-0.25)",
112 "badd(date(2737,12,30),1)", "badd(date(1,1,3),-1)", "bsub(date(2737,12,31),date(1,1,1))",
113 "<0070-01-01 Thu>", "<0001-01-01 Mon>", "<0010-01-01 Fri>", "<0000-01-01 Sat>", "<0039-12-31 Sat>", "<0040-01-01 Sun>",
114 "<0099-01-01 Fri>", "<0050-06-15 Thu 10:30>", "<0100-01-01 Fri>", "year(<0010-01-01 Fri>)", "unixtime(<0001-01-01 Mon>)",
67 ] 115 ]
68 116
117 /// Zones without daylight saving time, as `TZ` names them for Emacs and their offsets.
118 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
119 func datesInFixedZonesMatchCalc() throws {
120 let cases = ["unixtime(<2026-10-05 Mon>)", "unixtime(<2026-10-05 Mon 10:30>)", "unixtime(1791158400)",
121 "julian(<2026-10-05 Mon 12:00>)", "julian(2461319.5)", "julian(<2026-10-05 Mon>)"].map { ($0, "(float 8)") }
122 for zone in [("EST5", -5 * 3600), ("IST-5:30", 19800)] {
123 let skipped = try Self.compare(cases, zone: zone)
124 #expect(skipped == [], "\(zone.0) \(skipped)")
125 }
126 }
127
128 /// Every function and operator given dates where numbers go: what isn't refused must
129 /// match Calc.
130 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
131 func everythingOnDatesMatchesCalc() throws {
132 let functions = ["vsum", "vprod", "vcount", "vmean", "vmax", "vmin", "vmedian", "if", "vvar", "vpvar", "vsdev", "vpsdev",
133 "mod", "idiv", "fact", "dfact", "max", "min", "abs", "floor", "ceil", "trunc", "round", "sqrt", "exp", "ln",
134 "log10", "sin", "cos", "tan", "arcsin", "arccos", "arctan", "eq", "neq", "lt", "gt", "leq", "geq", "land",
135 "lor", "lnot", "percent", "float", "pfloat", "sign", "rounde", "roundu", "frac", "fdiv", "gcd", "lcm",
136 "choose", "perm", "pow", "exp10", "nroot", "hypot", "log", "sinh", "cosh", "tanh", "arcsinh", "arccosh",
137 "arctanh", "arctan2", "deg", "rad", "vflat", "vgmean", "vhmean", "vcov", "vpcov", "vcorr", "agmean", "date",
138 "year", "month", "day", "hour", "minute", "second", "yearday", "weekday", "newweek", "newmonth", "newyear",
139 "incmonth", "incyear", "badd", "bsub", "julian", "unixtime"]
140 let (d, t) = ("<2026-10-05 Mon>", "<2026-10-07 Wed 10:30>")
141 var cases: [String] = []
142 for f in functions {
143 for args in [d, t, "\(d),2", "2,\(d)", "\(t),1.5", "\(d),\(t)", "\(t),\(d)", "[\(d),\(t)]", "[\(d),2]", "[\(t)],[\(d)]", "1,\(d),2"] {
144 cases.append("\(f)(\(args))")
145 }
146 }
147 for op in ["+", "-", "*", "/", "%", "\\", "^", "==", "!=", "<", ">", "<=", ">=", "&&", "||"] {
148 cases += ["\(d)\(op)2", "2\(op)\(d)", "\(d)\(op)\(t)", "\(t)\(op)0.5", "\(t)\(op)\(d)", "\(d)\(op)nan"]
149 }
150 cases += ["-\(t)", "!\(d)", "\(d)%", "\(d)!", "\(d) 2", "2 \(d)"]
151 let skipped = try Self.compare(cases.map { ($0, "(float 8)") })
152 #expect(skipped.count < cases.count)
153 }
154
155 @Test func now() throws {
156 var modes = Calc.Modes()
157 modes.timeZone = TimeZone(secondsFromGMT: 3600)!
158 modes.now = Date(timeIntervalSince1970: 1_791_196_245)
159 #expect(try Calc.evaluate("now()", modes: modes) == "<2026-10-05 Mon 11:30>")
160 #expect(try Calc.evaluate("second(now())", modes: modes) == "45")
161 #expect(try Calc.evaluate("date(10,6)-newyear(now())", modes: modes) == "278")
162 modes.now = Date(timeIntervalSince1970: 1_791_158_400 - 3600)
163 #expect(try Calc.evaluate("now()", modes: modes) == "<2026-10-05 Mon 00:00>")
164 }
165
69 /// Constants, functions and syntax that only some tables use. 166 /// Constants, functions and syntax that only some tables use.
70 static let functions = [ 167 static let functions = [
71 // Grammar: juxtaposition, percent, factorials, fractions and radix integers. 168 // Grammar: juxtaposition, percent, factorials, fractions and radix integers.
@@ -126,13 +223,14 @@ struct CalcTests {
126 223
127 /// Each case through Calc and through `Calc.evaluate`, expecting the same text; returns the 224 /// Each case through Calc and through `Calc.evaluate`, expecting the same text; returns the
128 /// cases `Calc.evaluate` doesn't support. 225 /// cases `Calc.evaluate` doesn't support.
129 static func compare(_ cases: [(String, String)], precision: Int = 12) throws -> [String] { 226 static func compare(_ cases: [(String, String)], precision: Int = 12, zone: (name: String, offset: Int) = ("UTC", 0)) throws -> [String] {
130 let emacs = try CalcOracle.run(cases, precision: precision) 227 let emacs = try CalcOracle.run(cases, precision: precision, zone: zone.name)
131 #expect(emacs.count == cases.count) 228 #expect(emacs.count == cases.count)
132 var skipped: [String] = [] 229 var skipped: [String] = []
133 for (c, expected) in zip(cases, emacs) { 230 for (c, expected) in zip(cases, emacs) {
134 var modes = Calc.Modes() 231 var modes = Calc.Modes()
135 modes.precision = precision 232 modes.precision = precision
233 modes.timeZone = TimeZone(secondsFromGMT: zone.offset)!
136 let f = c.1.dropFirst().dropLast().split(separator: " ") 234 let f = c.1.dropFirst().dropLast().split(separator: " ")
137 let n = Int(f[1])! 235 let n = Int(f[1])!
138 switch f[0] { 236 switch f[0] {
@@ -212,6 +310,12 @@ struct CalcTests {
212 if precision <= 16 { 310 if precision <= 16 {
213 cases += ["vsum([0.1,0.2,0.3])", "vmean([1,2,4])", "vsum([1e-13,1,-1])", "vsdev([1.5,2.25,3e-12])", "0.7^-3"].map { ($0, "(float 0)") } 311 cases += ["vsum([0.1,0.2,0.3])", "vmean([1,2,4])", "vsum([1e-13,1,-1])", "vsdev([1.5,2.25,3e-12])", "0.7^-3"].map { ($0, "(float 0)") }
214 } 312 }
313 // Above 12 digits Calc keeps fractions of a second, which isn't supported.
314 if precision < 12 {
315 cases += ["<2026-10-05 Mon 08:30>+1", "<2026-10-05 Mon>+0.5", "julian(<2026-10-05 Mon 12:00>)", "unixtime(<2026-10-05 Mon 10:30>)",
316 "badd(<2026-10-09 Fri 10:00>,2.5)", "date(2026,1,1,10,30,15)", "minute(<2026-10-05 Mon 10:30>)",
317 "vsum([<2026-10-05 Mon 06:00>,0.1])"].map { ($0, "(float 0)") }
318 }
215 cases += ["vmax([1000., 1001])", "vmin([1001, 1000.])", "vmax([1234567890120., 1234567890123])", "1.1^10", 319 cases += ["vmax([1000., 1001])", "vmin([1001, 1000.])", "vmax([1234567890120., 1234567890123])", "1.1^10",
216 "8^(1:3)", "1.5^3"].map { ($0, "(float 0)") } 320 "8^(1:3)", "1.5^3"].map { ($0, "(float 0)") }
217 if precision <= 14 { 321 if precision <= 14 {
@@ -236,19 +340,37 @@ struct CalcTests {
236 } 340 }
237 } 341 }
238 342
239 @Test func unsupported() { 343 @Test func unsupported() throws {
240 for e in ["abc*2", "1/0", "vmean([])", "pi", "e", "phi", "gamma", "2 pi", "(-8)^(1/3)", "vvar([5])", "1<2<3", 344 for e in ["abc*2", "1/0", "vmean([])", "pi", "e", "phi", "gamma", "2 pi", "(-8)^(1/3)", "vvar([5])", "1<2<3",
241 "vmax([])", "vmin([])", "vrms([1,2])", "vmeane([1,2])", "vcov([1,2],[3])", "vcov([1],[2])", 345 "vmax([])", "vmin([])", "vrms([1,2])", "vmeane([1,2])", "vcov([1,2],[3])", "vcov([1],[2])",
242 "fdiv(7.5,2)", "fdiv(7,0)", "perm(5,6)", "log(8,1)", "log(0,2)", "log(-8,2)", "arctanh(1)", "arccosh(0.5)", 346 "fdiv(7.5,2)", "fdiv(7,0)", "perm(5,6)", "log(8,1)", "log(0,2)", "log(-8,2)", "arctanh(1)", "arccosh(0.5)",
243 "nroot(-8,3)", "vgmean([-1,2])", "vhmean([0,1])", "gcd(1.5,3)", "gcd(12,18,4)", "5%%3", "1:0", "1:2:3:4", 347 "nroot(-8,3)", "vgmean([-1,2])", "vhmean([0,1])", "gcd(1.5,3)", "gcd(12,18,4)", "5%%3", "1:0", "1:2:3:4",
244 "16#1.8", "16#FG", "2##11", "2.5!", "(-1)!", "(-3)!!", "choose(5.5,2)", "exp10(0.5)", "3!!!", 348 "16#1.8", "16#FG", "2##11", "2.5!", "(-1)!", "(-3)!!", "choose(5.5,2)", "exp10(0.5)", "3!!!",
245 "eq(1,1,1)", "percent(nan)", "frac(0.5,0.1)", "frac(1e-20)", 349 "eq(1,1,1)", "percent(nan)", "frac(0.5,0.1)", "frac(1e-20)",
246 "(2..5)", "[2..5]", "vmax([1..5])", "vcount([1..5])", "2...5", "(-8)^(1:3)", "(-2)^1.5", "0^-1", "0^0.", "ln(0)", "ln(-1)"] { 350 "(2..5)", "[2..5]", "vmax([1..5])", "vcount([1..5])", "2...5", "(-8)^(1:3)", "(-2)^1.5", "0^-1", "0^0.", "ln(0)", "ln(-1)",
351 // Calc leaves these date expressions unevaluated.
352 "<2026-10-05 Mon>*2", "2*<2026-10-05 Mon>", "<2026-10-05 Mon>/2", "<2026-10-05 Mon>*0", "<2026-10-05 Mon> < 5",
353 "vmedian([<2026-10-05 Mon>,<2026-10-07 Wed>])", "vmean([<2026-10-05 Mon>,1])", "vmean([<2026-10-05 Mon>])",
354 "vmean([<2026-10-05 Mon>,<2026-10-06 Tue>,<2026-10-10 Sat>])", "vvar([<2026-10-05 Mon>,<2026-10-07 Wed>])",
355 "max(<2026-10-05 Mon>,1)", "if(<2026-10-05 Mon>,1,2)", "round(<2026-10-05 Mon 13:00>,1)", "date(2026,13,1)",
356 "date(2026,2,32)", "date(2026.5,1,1)", "date(2026,1,1,10,30,1.5)", "date([1,2])", "year([1,2])",
357 "newweek(<2026-10-15 Thu>,7)", "newyear(<2026-10-15 Thu>,400)", "incmonth(<2026-10-05 Mon>,1.5)",
358 "badd(<2026-10-09 Fri>,<2026-10-09 Fri>)", "bsub(5,1)", "now(5)", "julian(<2026-10-05 Mon>,5)", "1<<2026-10-05 Mon>",
359 // Outside the years 1 to 2737, Calc's holiday range.
360 "badd(date(2737,12,31),1)", "badd(<2026-10-05 Mon>,200000)", "bsub(date(2738,1,10),date(2026,1,1))",
361 "badd(date(-100,1,3),1)", "badd(date(1,1,3),-3)", "bsub(date(1,1,10),date(-1,12,20))", "badd(date(10000,1,3),1)",
362 // Calc leaves abs of day number 0 unevaluated.
363 "abs(date(1,1,1)-1)", "abs(date(-1,12,31))"] {
247 #expect(throws: Calc.Unsupported.self, "\(e)") { try Calc.evaluate(e) } 364 #expect(throws: Calc.Unsupported.self, "\(e)") { try Calc.evaluate(e) }
248 } 365 }
249 var modes = Calc.Modes() 366 var modes = Calc.Modes()
367 // Calc's daylight saving rules aren't reproduced.
368 modes.timeZone = TimeZone(identifier: "America/New_York")!
369 #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("unixtime(<2026-10-05 Mon>)", modes: modes) }
370 #expect(try Calc.evaluate("julian(<2026-10-05 Mon>)", modes: modes) == "2461319")
250 modes.precision = 15 371 modes.precision = 15
251 #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("sinh(1)", modes: modes) } 372 #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("sinh(1)", modes: modes) }
373 #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("<2026-10-05 Mon 10:00>+1", modes: modes) }
252 modes.precision = 19 374 modes.precision = 19
253 #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("1+1", modes: modes) } 375 #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("1+1", modes: modes) }
254 } 376 }
Tests/OrgCoreTests/TableFormulaTests.swift +25
@@ -69,6 +69,31 @@ struct TableFormulaTests {
69 "#+NAME: t1\n| 5 | 6 |\n| 1 | 2 |\n\n#+NAME: t2\n| 7 | 8 |\n\n| name | val | sum |\n|------+-----+-----|\n| t1 | | |\n| t2 | | |\n#+TBLFM: $2=remote($1,@1$1)::$3=vsum(remote(t1,$1..$2))+vsum($1..$2)\n", 69 "#+NAME: t1\n| 5 | 6 |\n| 1 | 2 |\n\n#+NAME: t2\n| 7 | 8 |\n\n| name | val | sum |\n|------+-----+-----|\n| t1 | | |\n| t2 | | |\n#+TBLFM: $2=remote($1,@1$1)::$3=vsum(remote(t1,$1..$2))+vsum($1..$2)\n",
70 ] 70 ]
71 71
72 /// Timestamps in fields and formulas, with and without the duration flags, and Calc's
73 /// date functions.
74 static let dates = [
75 "| d1 | d2 | diff | T | t | U | N |\n|----+----+------+---+---+---+---|\n| <2026-01-01 Thu> | <2026-01-03 Sat> | | | | | |\n| <2026-01-01 Thu 10:00> | <2026-01-03 Sat 12:30> | | | | | |\n| [2026-01-01 Thu] | <2026-01-03 Sat 00:00> | | | | | |\n#+TBLFM: $3=$2-$1::$4=$2-$1;T::$5=$2-$1;t::$6=$2-$1;U::$7=$2-$1;N\n",
76 "| d | later | T | left |\n|---+-------+---+------|\n| <2026-10-05 Mon 00:00> | | | |\n| <2026-10-05 Mon 23:30> | | | |\n| [2026-10-05 Mon 12:00] | | | |\n#+TBLFM: $2=$1+0.5::$3=$1+1;T::$4=<2026-12-25 Fri>-$1\n",
77 "| d | y | m | wd | yd | h | next | start | week | year |\n|---+---+---+----+----+---+------+-------+------+------|\n| <2026-10-05 Mon> | | | | | | | | | |\n| <2026-01-31 Sat 09:15> | | | | | | | | | |\n| [2024-02-29 Thu] | | | | | | | | | |\n#+TBLFM: $2=year($1)::$3=month($1)::$4=weekday($1)::$5=yearday($1)::$6=hour($1)+minute($1)::$7=incmonth($1,1)::$8=newmonth($1)::$9=newweek($1,1)::$10=incyear($1)\n",
78 "| d | due | days | jd | n | back |\n|---+-----+------+----+---+------|\n| <2026-10-09 Fri> | | | | | |\n| <2026-10-10 Sat 08:00> | | | | | |\n#+TBLFM: $2=badd($1,3)::$3=bsub(badd($1,10),$1)::$4=julian(floor($1))::$5=date($1)::$6=date(2026,1,1)+floor($1-date(2026,1,1))\n",
79 "| d | abs | next |\n|---+-----+------|\n| <2026-01-01 Thu> | | |\n| <0070-01-01 Thu> | | |\n| [0010-01-01 Fri] | | |\n#+TBLFM: $2=abs(-$1)::$3=$1+1\n",
80 "| d |\n|---|\n| <2026-10-05 Mon> |\n| <2026-10-07 Wed 06:00> |\n|---|\n| |\n| |\n| |\n#+TBLFM: @4$1=vmean(@I..@II)::@5$1=vmin(@I..@II)::@6$1=vmax(@I..@II)\n",
81 ]
82
83 /// Results that aren't numbers under `N` and the duration flags: `#ERROR`, or for a
84 /// duration an error.
85 static let numericResults = [
86 "| a | b | c | d | e | f | g |\n|---+---+---+---+---+---+---|\n| <2026-01-01 Thu> | | | | | | |\n#+TBLFM: $2=<2026-01-01 Thu>+$1;N::$3=<2026-01-01 Thu>;E::$4=<2026-01-01 Thu>;EN::$5=<2026-01-01 Thu>;ET::$6=nan;N::$7=1/3;NF\n",
87 "| a | b |\n|---+---|\n| 1 | |\n#+TBLFM: $2=$1/3;TF\n",
88 "| a | b |\n|---+---|\n| 1 | |\n#+TBLFM: $2=nan;T\n",
89 "| a | b |\n|---+---|\n| <2026-01-01 Thu> | |\n#+TBLFM: $2=<2026-12-25 Fri>-$1;U\n",
90 ]
91
92 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
93 func datesMatchEmacs() throws {
94 try compare(Self.dates + Self.numericResults, fallbacksAllowed: false)
95 }
96
72 @Test func remoteFindsTablesByIDInOtherFiles() { 97 @Test func remoteFindsTablesByIDInOtherFiles() {
73 let other = "* Elsewhere\n:PROPERTIES:\n:ID: far\n:END:\n| v |\n|---|\n| 7 |\n" 98 let other = "* Elsewhere\n:PROPERTIES:\n:ID: far\n:END:\n| v |\n|---|\n| 7 |\n"
74 RemoteTables.fileWithID = { $0 == "far" ? other : nil } 99 RemoteTables.fileWithID = { $0 == "far" ? other : nil }
docs/manual/guide/10-tables.org +36
@@ -429,6 +429,42 @@ times. A date plus a number is a date, written back as an inactive timestamp:
429,#+TBLFM: $3=$2-$1::$4=$1+7 429,#+TBLFM: $3=$2-$1::$4=$1+7
430#+END_SRC 430#+END_SRC
431 431
432A date is its day number underneath, counted from 1 January of year 1, so the sum of two
433dates is a number and =vmean= of two dates is the day number halfway between them.
434=vsum=, =vmax=, =vmin=, =max=, =min=, =abs= and the comparisons work on dates; =floor=,
435=ceil=, =trunc= and =round= keep a date and drop or round its time. A timestamp with a
436time, even =00:00=, keeps showing one. Calc leaves =abs= of day 0 (=<-1-12-31>=)
437unevaluated, so that needs Emacs.
438
439| Function | Result |
440|--------------------------------------------+------------------------------------------------------------------------------------|
441| =year=, =month=, =day= | Parts of the date. |
442| =hour=, =minute=, =second= | Parts of the time, 0 for a date without one. |
443| =weekday= | 0 for Sunday to 6 for Saturday. |
444| =yearday= | Day of the year, 1 for 1 January. |
445| =date(y, m, d)=, =date(y, m, d, h, mi, s)= | The date, with a time when an hour is given. =date(m, d)= is this year. |
446| =date(d)= | The day number of date /d/, or the date of day number /d/. |
447| =now()= | The current date and time. |
448| =incmonth(d, n)=, =incyear(d, n)= | /n/ months or years later (1 by default), on the last day if the month is shorter. |
449| =newmonth(d, n)=, =newyear(d, n)= | Day /n/ of the month or year (1 by default; 0 is the last day). |
450| =newweek(d, w)= | The day on or before /d/ that falls on weekday /w/ (0, Sunday, by default). |
451| =badd(d, n)=, =bsub(d, n)= | /n/ business days later or earlier, skipping Saturdays and Sundays. |
452| =bsub(d1, d2)= | Business days from /d2/ to /d1/. |
453| =julian(d)= | The Julian day number of /d/, or the date of a Julian day number. |
454| =unixtime(d)= | Seconds since 1970-01-01 00:00 UTC, or the date of a number of seconds. |
455
456As in Calc, a timestamp year under 100 is read as 19xx or 20xx: 00 to 39 is 20xx, 40 to
45799 is 19xx. =badd= and =bsub= work only for dates in the years 1 to 2737, the range of
458Calc's holiday table; outside it they need Emacs, which leaves them unevaluated.
459
460=julian= of a date with a time and =unixtime= use the local time zone. Emacs applies
461the current year's daylight saving rules to every date, which orgstar doesn't, so in a
462time zone with daylight saving time these need Emacs.
463
464With =N=, =T=, =U= or =t= a timestamp field counts as 0. A result that is a date is
465=#ERROR= with =N=, and with =T=, =U= or =t= it stops the recalculation with the error
466Org gives.
467
432** Lisp formulas 468** Lisp formulas
433 469
434A formula that starts with ='(= is Emacs Lisp. Each reference becomes a Lisp string, 470A formula that starts with ='(= is Emacs Lisp. Each reference becomes a Lisp string,
l10n/Localizable.xcstrings +34
@@ -34082,6 +34082,40 @@
34082 } 34082 }
34083 } 34083 }
34084 }, 34084 },
34085 "daylight saving time": {
34086 "localizations": {
34087 "de": {
34088 "stringUnit": {
34089 "state": "translated",
34090 "value": "Sommerzeit"
34091 }
34092 },
34093 "es": {
34094 "stringUnit": {
34095 "state": "translated",
34096 "value": "horario de verano"
34097 }
34098 },
34099 "fr": {
34100 "stringUnit": {
34101 "state": "translated",
34102 "value": "heure d’été"
34103 }
34104 },
34105 "ja": {
34106 "stringUnit": {
34107 "state": "translated",
34108 "value": "夏時間"
34109 }
34110 },
34111 "pt-BR": {
34112 "stringUnit": {
34113 "state": "translated",
34114 "value": "horário de verão"
34115 }
34116 }
34117 }
34118 },
34085 "division by zero": { 34119 "division by zero": {
34086 "localizations": { 34120 "localizations": {
34087 "de": { 34121 "de": {