Commit 22ff42f0ad

22ff42f0ad29d59255e2ac93e0b3a28f66fca672

parent: fa36a13d84

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-20 19:17 UTC

Calc dates: date functions, business days, date sums and times at 00:00

Layout: unified · split

Sources/OrgApp/TableReason.swift +1
@@ -103,6 +103,7 @@ public enum TableReason {
103103 case "constants that refer to themselves": return String(localized: "constants that refer to themselves", comment: comment)
104104 case "date arithmetic": return String(localized: "date arithmetic", comment: comment)
105105 case "date syntax": return String(localized: "date syntax", comment: comment)
106 case "daylight saving time": return String(localized: "daylight saving time", comment: comment)
106107 case "division by zero": return String(localized: "division by zero", comment: comment)
107108 case "duration size": return String(localized: "duration size", comment: comment)
108109 case "empty vector": return String(localized: "empty vector", comment: comment)
Sources/OrgCore/Compute/Calc.swift +237 −18
@@ -42,6 +42,10 @@ public enum Calc {
4242 public var degrees = true
4343 /// `calc-prefer-frac`: dividing integers gives a fraction.
4444 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
4549 public init() {}
4650 }
4751
@@ -56,7 +60,7 @@ public enum Calc {
5660 let value = try Evaluator(modes: modes).eval(tree)
5761 if numeric {
5862 switch value {
59 case .int, .float: break
63 case .int, .float, .frac: break
6064 default: throw Failure("Number expected")
6165 }
6266 }
@@ -73,6 +77,7 @@ public enum Calc {
7377 static func extra(_ n: Int, _ body: () throws -> Value) throws -> Value {
7478 let v = try $precision.withValue(precision + n, operation: body)
7579 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)) }
7681 return v
7782 }
7883
@@ -272,7 +277,8 @@ public enum Calc {
272277 switch (a, b) {
273278 case (.nan, .vector), (.vector, .nan): throw Unsupported("vector arithmetic")
274279 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)
276282 case (.date(let d), _): return .date(try add(d, b))
277283 case (_, .date(let d)): return .date(try add(a, d))
278284 default: break
@@ -310,16 +316,14 @@ public enum Calc {
310316 case .float(let m, let e): return .float(-m, e)
311317 case .frac(let n, let d): return .frac(-n, d)
312318 case .vector: throw Unsupported("vector arithmetic")
313 case .date: throw Unsupported("date arithmetic")
319 case .date(let d): return .date(try negate(d))
314320 case .nan: return .nan
315321 }
316322 }
317323
318324 /// `a - b`: a date less a date is the days between them.
319325 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)) }
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))
326 try add(a, try negate(b))
323327 }
324328
325329 static func isNaN(_ a: Value, _ b: Value) -> Bool {
@@ -768,16 +772,13 @@ public enum Calc {
768772
769773 static let weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
770774
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.
772777 static func formatDate(_ value: Value) throws -> String {
773 let days = try double(value)
774 let day = Int(days.rounded(.down))
775 let date = Days.date(day)
776 var text = String(format: "%04d-%02d-%02d ", date.year, date.month, date.day) + weekdays[Days.weekday(day)]
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 }
778 let dt = try dateParts(value)
779 let year = dt.year > 0 && dt.year < 100 ? "+\(dt.year)" : String(dt.year)
780 var text = year + String(format: "-%02d-%02d ", dt.month, dt.day) + weekdays[Days.weekday(try floorInt(value))]
781 if let time = dt.time { text += String(format: " %02d:%02d", time.hour, time.minute) }
781782 return text
782783 }
783784
@@ -789,9 +790,96 @@ public enum Calc {
789790 }
790791 let day = Days.absolute(year: Int(m.1)!, month: Int(m.2)!, day: Int(m.3)!)
791792 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)
793 if seconds == 0 { return .date(.int(day)) }
794 return .date(try add(.int(day), try divide(.int(seconds), .int(86400))))
793 return try dateTime(day, hour * 3600 + minute * 60 + (m.6.flatMap { Int($0) } ?? 0))
794 }
795
796 // MARK: - Dates
797
798 /// Calc numbers years without a year 0: -1 comes before 1.
799 static func astronomical(_ year: Int) -> Int { year > 0 ? year : year == 0 ? 0 : year + 1 }
800
801 /// `math-absolute-from-gregorian-dt`.
802 static func absolute(_ year: Int, _ month: Int, _ day: Int) throws -> Int {
803 guard abs(year) < 1_000_000_000 else { throw Unsupported("number size") }
804 return Days.absolute(year: astronomical(year), month: month, day: day)
805 }
806
807 /// `math-days-in-month`.
808 static func daysInMonth(_ year: Int, _ month: Int) throws -> Int {
809 try absolute(year, month + 1, 1) - absolute(year, month, 1)
810 }
811
812 /// `math-dt-to-date` with a time of day: a float day number.
813 static func dateTime(_ day: Int, _ seconds: Int) throws -> Value {
814 .date(try add(try float(.int(day)), try divide(.int(seconds), .float(864, 2))))
815 }
816
817 /// `math-dt-to-date`.
818 static func dateValue(_ year: Int, _ month: Int, _ day: Int, _ time: (hour: Int, minute: Int, second: Int)? = nil) throws -> Value {
819 guard (1...12).contains(month), (1...31).contains(day) else { throw Unsupported("arguments") }
820 let n = try absolute(year, month, day)
821 guard let time else { return .date(.int(n)) }
822 guard [time.hour, time.minute, time.second].allSatisfy({ abs($0) < 1_000_000 }) else { throw Unsupported("arguments") }
823 return try dateTime(n, time.hour * 3600 + time.minute * 60 + time.second)
824 }
825
826 /// The day number of a date form, or a real number, which Calc's date functions also take.
827 static func dayNumber(_ v: Value) throws -> Value {
828 let x: Value = if case .date(let d) = v { d } else { v }
829 _ = try sign(x)
830 return x
831 }
832
833 /// `math-date-to-dt`: the day, with the time of day when the day number isn't an integer.
834 static func dateParts(_ v: Value) throws -> (year: Int, month: Int, day: Int, time: (hour: Int, minute: Int, second: Int)?) {
835 let x = try dayNumber(v)
836 let day = try floorInt(x)
837 guard abs(day) < 100_000_000_000 else { throw Unsupported("number size") }
838 let date = Days.date(day)
839 let year = date.year > 0 ? date.year : date.year - 1
840 if case .int = x { return (year, date.month, date.day, nil) }
841 // Above 12 digits Calc keeps fractions of a second.
842 guard precision <= 12 else { throw Unsupported("calc precision") }
843 let seconds = try trunc(try round(try multiply(try subtract(x, .int(day)), .int(86400)), even: false))
844 return (year, date.month, date.day, (seconds / 3600, seconds / 60 % 60, seconds % 60))
845 }
846
847 /// `math-to-business-day`, with Calc's default holidays: Saturdays and Sundays.
848 static func toBusinessDay(_ v: Value) throws -> (Value, holiday: Bool) {
849 let x = try dayNumber(v)
850 let day = try floorInt(x)
851 let weekday = Days.weekday(day)
852 let delta = day / 7 * 2 + (weekday > 0 ? 1 : 0)
853 return (try add(.int(day - delta), try subtract(x, .int(day))), weekday == 0 || weekday == 6)
854 }
855
856 /// `math-from-business-day`.
857 static func fromBusinessDay(_ n: Value) throws -> Value {
858 var day = try floorInt(n)
859 let time = try subtract(n, .int(day))
860 var left = ((day % 5) + 5) % 5
861 day += day / 5 * 2
862 var weekday = 0
863 while true {
864 if weekday == 0 || weekday == 6 {
865 day += 1
866 } else {
867 left -= 1
868 if left < 0 { break }
869 }
870 weekday += 1
871 }
872 return .date(try add(.int(day), time))
873 }
874
875 /// `calcFunc-tzone` for the local zone, in seconds. Calc applies the current year's
876 /// daylight saving rules to every date, which isn't reproduced, so only zones without
877 /// daylight saving time are supported.
878 static func zoneOffset(_ zone: TimeZone) throws -> Int {
879 guard !zone.isDaylightSavingTime(), zone.nextDaylightSavingTimeTransition == nil else {
880 throw Unsupported("daylight saving time")
881 }
882 return -zone.secondsFromGMT()
795883 }
796884
797885 // MARK: - Parsing
@@ -856,6 +944,8 @@ public enum Calc {
856944
857945 mutating func comparison() throws -> Node {
858946 let left = try sum()
947 // Calc reads `<<` and `>>` as one token, so `1<<2026-10-05 Mon>` is a syntax error.
948 if take("<<") || take(">>") { throw Unsupported("formula syntax") }
859949 for (token, op) in [("==", "="), ("!=", "≠"), ("<=", "≤"), (">=", "≥"), ("<", "<"), (">", ">")] where take(token) {
860950 let right = try sum()
861951 if let next = peek(), "=!<>".contains(next) { throw Unsupported("chained comparison") }
@@ -1199,6 +1289,20 @@ public enum Calc {
11991289 return args[0]
12001290 }
12011291
1292 /// An integer argument, from an integer or a float with an integer value
1293 /// (`math-messy-integerp`).
1294 func integer(_ v: Value) throws -> Int {
1295 guard isWhole(v) else { throw Unsupported("arguments") }
1296 return try trunc(v)
1297 }
1298
1299 /// The local date and time `now()` reads.
1300 func clock() -> DateComponents {
1301 var calendar = Calendar(identifier: .gregorian)
1302 calendar.timeZone = modes.timeZone
1303 return calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: modes.now ?? Date())
1304 }
1305
12021306 func radians(_ x: Double) -> Double { modes.degrees ? x * .pi / 180 : x }
12031307 func angle(_ x: Double) -> Double { modes.degrees ? x * 180 / .pi : x }
12041308
@@ -1229,6 +1333,8 @@ public enum Calc {
12291333 case "vmedian":
12301334 var items = try elements(args)
12311335 guard !items.isEmpty else { throw Unsupported("empty vector") }
1336 // Calc leaves the median of dates unevaluated.
1337 if items.contains(where: { if case .date = $0 { true } else { false } }) { throw Unsupported("arguments") }
12321338 try items.sort { try compare($0, $1) < 0 }
12331339 if items.count % 2 == 1 { return items[items.count / 2] }
12341340 return try divide(try add(items[items.count / 2 - 1], items[items.count / 2]), .int(2))
@@ -1261,8 +1367,10 @@ public enum Calc {
12611367 return best
12621368 case "abs":
12631369 let x = try one(args)
1370 if case .date = x { return x }
12641371 return try compare(x, .int(0)) < 0 ? try negate(x) : x
12651372 case "floor", "ceil", "trunc":
1373 if args.count == 1, case .date(let d) = args[0] { return .date(try call(name, [d])) }
12661374 var x = try one(args)
12671375 if case .frac(let n, let d) = x { x = try divide(.int(n), .int(d)) }
12681376 if case .int = x { return x }
@@ -1272,6 +1380,10 @@ public enum Calc {
12721380 return .int(i)
12731381 case "round":
12741382 guard args.count == 1 || args.count == 2 else { throw Unsupported("arguments") }
1383 if case .date(let d) = args[0] {
1384 guard args.count == 1 else { throw Unsupported("arguments") }
1385 return .date(try call(name, [d]))
1386 }
12751387 var x = args[0]
12761388 if case .frac(let n, let d) = x { x = try divide(.int(n), .int(d)) }
12771389 if args.count == 2 {
@@ -1533,6 +1645,113 @@ public enum Calc {
15331645 }
15341646 throw Unsupported("number")
15351647 }
1648 case "now":
1649 guard args.isEmpty else { throw Unsupported("arguments") }
1650 let c = clock()
1651 return try dateValue(c.year!, c.month!, c.day!, (c.hour!, c.minute!, c.second!))
1652 case "date":
1653 // `date(d)` converts between a date and its day number; otherwise the
1654 // arguments are [year,] month, day[, hour[, minute[, second]]].
1655 if args.count == 1 {
1656 if case .date(let d) = args[0] { return d }
1657 return .date(try dayNumber(args[0]))
1658 }
1659 guard (2...6).contains(args.count) else { throw Unsupported("arguments") }
1660 let n = try args.map(integer)
1661 if n.count == 2 { return try dateValue(clock().year!, n[0], n[1]) }
1662 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)
1663 case "year", "month", "day", "hour", "minute", "second", "yearday":
1664 let dt = try dateParts(try one(args))
1665 switch name {
1666 case "year": return .int(dt.year)
1667 case "month": return .int(dt.month)
1668 case "day": return .int(dt.day)
1669 case "hour": return .int(dt.time?.hour ?? 0)
1670 case "minute": return .int(dt.time?.minute ?? 0)
1671 case "second": return .int(dt.time?.second ?? 0)
1672 default: return .int(try absolute(dt.year, dt.month, dt.day) - absolute(dt.year, 1, 1) + 1)
1673 }
1674 case "weekday":
1675 return .int(Days.weekday(try floorInt(try dayNumber(try one(args)))))
1676 case "newweek":
1677 guard (1...2).contains(args.count) else { throw Unsupported("arguments") }
1678 let day = try floorInt(try dayNumber(args[0]))
1679 let weekday = args.count > 1 ? try integer(args[1]) : 0
1680 guard (0...6).contains(weekday) else { throw Unsupported("arguments") }
1681 return .date(.int(day - Days.weekday(day - weekday)))
1682 case "newmonth":
1683 guard (1...2).contains(args.count) else { throw Unsupported("arguments") }
1684 var day = args.count > 1 ? try integer(args[1]) : 1
1685 guard (0...31).contains(day) else { throw Unsupported("arguments") }
1686 let dt = try dateParts(args[0])
1687 let days = try daysInMonth(dt.year, dt.month)
1688 day = day == 0 || day > days ? days - 1 : day - 1
1689 return .date(.int(try absolute(dt.year, dt.month, 1) + day))
1690 case "newyear":
1691 guard (1...2).contains(args.count) else { throw Unsupported("arguments") }
1692 var day = args.count > 1 ? try integer(args[1]) : 1
1693 let dt = try dateParts(args[0])
1694 if (-12 ... -1).contains(day) { return .date(.int(try absolute(dt.year, -day, 1))) }
1695 guard (0...366).contains(day) else { throw Unsupported("arguments") }
1696 let days = try daysInMonth(dt.year, 2) == 29 ? 366 : 365
1697 if day == 0 || day > days { day = days }
1698 return .date(.int(try absolute(dt.year, 1, 1) + day - 1))
1699 case "incmonth", "incyear":
1700 guard (1...2).contains(args.count) else { throw Unsupported("arguments") }
1701 let step = args.count > 1 ? args[1] : .int(1)
1702 let months = try integer(name == "incyear" ? try multiply(step, .int(12)) : step)
1703 guard abs(months) < 1_000_000_000 else { throw Unsupported("arguments") }
1704 let dt = try dateParts(args[0])
1705 let m = dt.month - 1 + months
1706 let extra = m >= 0 ? m / 12 : (m - 11) / 12
1707 let month = m - extra * 12 + 1
1708 var year = dt.year + extra
1709 let day = min(dt.day, try daysInMonth(year, month))
1710 // Past the year zero, which Calc doesn't have.
1711 if dt.year > 0, year <= 0 { year -= 1 }
1712 if dt.year < 0, year >= 0 { year += 1 }
1713 return try dateValue(year, month, day, dt.time)
1714 case "badd", "bsub":
1715 guard args.count == 2 else { throw Unsupported("arguments") }
1716 var (a, b) = (args[0], args[1])
1717 if name == "bsub" {
1718 guard case .date = a else { throw Unsupported("arguments") }
1719 if case .date = b {
1720 if try compare(a, b) < 0 { return try negate(try call(name, [b, a])) }
1721 let (x, xHoliday) = try toBusinessDay(a)
1722 let (y, yHoliday) = try toBusinessDay(b)
1723 return try add(try subtract(x, y), .int(yHoliday && !xHoliday ? 1 : 0))
1724 }
1725 b = try negate(b)
1726 }
1727 if case .date = b {
1728 if case .date = a { throw Unsupported("arguments") }
1729 (a, b) = (b, a)
1730 }
1731 guard case .date = a else { throw Unsupported("arguments") }
1732 if try sign(b) == 0 { return a }
1733 let (day, holiday) = try toBusinessDay(a)
1734 return try fromBusinessDay(try add(day, holiday && sign(b) > 0 ? try subtract(b, .int(1)) : b))
1735 case "julian":
1736 // `math-julian-date-beginning`: 1721424.5 days before day 0.
1737 let x = try one(args)
1738 if case .date(let d) = x {
1739 if case .int = d { return try add(d, .int(1721425)) }
1740 return try add(d, try add(.float(17214245, -1), try divide(.int(try zoneOffset(modes.timeZone)), .float(864, 2))))
1741 }
1742 if case .int(let d) = x { return .date(try add(.int(d), .int(-1721425))) }
1743 let shifted = try subtract(try dayNumber(x), .float(17214245, -1))
1744 return .date(try subtract(shifted, try divide(.int(try zoneOffset(modes.timeZone)), .float(864, 2))))
1745 case "unixtime":
1746 // `math-unix-epoch`: day 719163.
1747 let x = try one(args)
1748 if case .date(let d) = x {
1749 guard precision <= 12 else { throw Unsupported("calc precision") }
1750 let seconds = try round(try multiply(try subtract(d, .int(719163)), .int(86400)), even: false)
1751 return try add(seconds, .int(try zoneOffset(modes.timeZone)))
1752 }
1753 let day = try add(.int(719163), try divide(try dayNumber(x), .float(864, 2)))
1754 return .date(try subtract(day, try divide(.int(try zoneOffset(modes.timeZone)), .float(864, 2))))
15361755 default:
15371756 throw Unsupported("function \(name)")
15381757 }
Sources/OrgCore/Compute/TableFormulas.swift +3 −1
@@ -632,7 +632,9 @@ extension EmacsBuffer {
632632 } else {
633633 do {
634634 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)\")") }
636638 (result, fmt) = ("#ERROR", nil)
637639 }
638640 }
Tests/OrgCoreTests/CalcTests.swift +118 −6
@@ -4,7 +4,7 @@ import Testing
44
55/// Runs `calc-eval` with org's table modes over a list of expressions.
66enum 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] {
88 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-calc-\(UUID().uuidString)")
99 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
1010 defer { try? FileManager.default.removeItem(at: folder) }
@@ -33,7 +33,7 @@ enum CalcOracle {
3333 (with-temp-file (getenv "ORACLE_OUTPUT")
3434 (insert (json-encode (vconcat results)))))
3535 """#.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])
3737 return try JSONDecoder().decode([String].self, from: Data(contentsOf: output))
3838 }
3939}
@@ -64,8 +64,100 @@ struct CalcTests {
6464 "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)",
6565 "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])",
6666 "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>)",
67110 ]
68111
112 /// Zones without daylight saving time, as `TZ` names them for Emacs and their offsets.
113 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
114 func datesInFixedZonesMatchCalc() throws {
115 let cases = ["unixtime(<2026-10-05 Mon>)", "unixtime(<2026-10-05 Mon 10:30>)", "unixtime(1791158400)",
116 "julian(<2026-10-05 Mon 12:00>)", "julian(2461319.5)", "julian(<2026-10-05 Mon>)"].map { ($0, "(float 8)") }
117 for zone in [("EST5", -5 * 3600), ("IST-5:30", 19800)] {
118 let skipped = try Self.compare(cases, zone: zone)
119 #expect(skipped == [], "\(zone.0) \(skipped)")
120 }
121 }
122
123 /// Every function and operator given dates where numbers go: what isn't refused must
124 /// match Calc.
125 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
126 func everythingOnDatesMatchesCalc() throws {
127 let functions = ["vsum", "vprod", "vcount", "vmean", "vmax", "vmin", "vmedian", "if", "vvar", "vpvar", "vsdev", "vpsdev",
128 "mod", "idiv", "fact", "dfact", "max", "min", "abs", "floor", "ceil", "trunc", "round", "sqrt", "exp", "ln",
129 "log10", "sin", "cos", "tan", "arcsin", "arccos", "arctan", "eq", "neq", "lt", "gt", "leq", "geq", "land",
130 "lor", "lnot", "percent", "float", "pfloat", "sign", "rounde", "roundu", "frac", "fdiv", "gcd", "lcm",
131 "choose", "perm", "pow", "exp10", "nroot", "hypot", "log", "sinh", "cosh", "tanh", "arcsinh", "arccosh",
132 "arctanh", "arctan2", "deg", "rad", "vflat", "vgmean", "vhmean", "vcov", "vpcov", "vcorr", "agmean", "date",
133 "year", "month", "day", "hour", "minute", "second", "yearday", "weekday", "newweek", "newmonth", "newyear",
134 "incmonth", "incyear", "badd", "bsub", "julian", "unixtime"]
135 let (d, t) = ("<2026-10-05 Mon>", "<2026-10-07 Wed 10:30>")
136 var cases: [String] = []
137 for f in functions {
138 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"] {
139 cases.append("\(f)(\(args))")
140 }
141 }
142 for op in ["+", "-", "*", "/", "%", "\\", "^", "==", "!=", "<", ">", "<=", ">=", "&&", "||"] {
143 cases += ["\(d)\(op)2", "2\(op)\(d)", "\(d)\(op)\(t)", "\(t)\(op)0.5", "\(t)\(op)\(d)", "\(d)\(op)nan"]
144 }
145 cases += ["-\(t)", "!\(d)", "\(d)%", "\(d)!", "\(d) 2", "2 \(d)"]
146 let skipped = try Self.compare(cases.map { ($0, "(float 8)") })
147 #expect(skipped.count < cases.count)
148 }
149
150 @Test func now() throws {
151 var modes = Calc.Modes()
152 modes.timeZone = TimeZone(secondsFromGMT: 3600)!
153 modes.now = Date(timeIntervalSince1970: 1_791_196_245)
154 #expect(try Calc.evaluate("now()", modes: modes) == "<2026-10-05 Mon 11:30>")
155 #expect(try Calc.evaluate("second(now())", modes: modes) == "45")
156 #expect(try Calc.evaluate("date(10,6)-newyear(now())", modes: modes) == "278")
157 modes.now = Date(timeIntervalSince1970: 1_791_158_400 - 3600)
158 #expect(try Calc.evaluate("now()", modes: modes) == "<2026-10-05 Mon 00:00>")
159 }
160
69161 /// Constants, functions and syntax that only some tables use.
70162 static let functions = [
71163 // Grammar: juxtaposition, percent, factorials, fractions and radix integers.
@@ -126,13 +218,14 @@ struct CalcTests {
126218
127219 /// Each case through Calc and through `Calc.evaluate`, expecting the same text; returns the
128220 /// cases `Calc.evaluate` doesn't support.
129 static func compare(_ cases: [(String, String)], precision: Int = 12) throws -> [String] {
130 let emacs = try CalcOracle.run(cases, precision: precision)
221 static func compare(_ cases: [(String, String)], precision: Int = 12, zone: (name: String, offset: Int) = ("UTC", 0)) throws -> [String] {
222 let emacs = try CalcOracle.run(cases, precision: precision, zone: zone.name)
131223 #expect(emacs.count == cases.count)
132224 var skipped: [String] = []
133225 for (c, expected) in zip(cases, emacs) {
134226 var modes = Calc.Modes()
135227 modes.precision = precision
228 modes.timeZone = TimeZone(secondsFromGMT: zone.offset)!
136229 let f = c.1.dropFirst().dropLast().split(separator: " ")
137230 let n = Int(f[1])!
138231 switch f[0] {
@@ -212,6 +305,12 @@ struct CalcTests {
212305 if precision <= 16 {
213306 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)") }
214307 }
308 // Above 12 digits Calc keeps fractions of a second, which isn't supported.
309 if precision < 12 {
310 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>)",
311 "badd(<2026-10-09 Fri 10:00>,2.5)", "date(2026,1,1,10,30,15)", "minute(<2026-10-05 Mon 10:30>)",
312 "vsum([<2026-10-05 Mon 06:00>,0.1])"].map { ($0, "(float 0)") }
313 }
215314 cases += ["vmax([1000., 1001])", "vmin([1001, 1000.])", "vmax([1234567890120., 1234567890123])", "1.1^10",
216315 "8^(1:3)", "1.5^3"].map { ($0, "(float 0)") }
217316 if precision <= 14 {
@@ -236,19 +335,32 @@ struct CalcTests {
236335 }
237336 }
238337
239 @Test func unsupported() {
338 @Test func unsupported() throws {
240339 for e in ["abc*2", "1/0", "vmean([])", "pi", "e", "phi", "gamma", "2 pi", "(-8)^(1/3)", "vvar([5])", "1<2<3",
241340 "vmax([])", "vmin([])", "vrms([1,2])", "vmeane([1,2])", "vcov([1,2],[3])", "vcov([1],[2])",
242341 "fdiv(7.5,2)", "fdiv(7,0)", "perm(5,6)", "log(8,1)", "log(0,2)", "log(-8,2)", "arctanh(1)", "arccosh(0.5)",
243342 "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",
244343 "16#1.8", "16#FG", "2##11", "2.5!", "(-1)!", "(-3)!!", "choose(5.5,2)", "exp10(0.5)", "3!!!",
245344 "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)"] {
345 "(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)",
346 // Calc leaves these date expressions unevaluated.
347 "<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",
348 "vmedian([<2026-10-05 Mon>,<2026-10-07 Wed>])", "vmean([<2026-10-05 Mon>,1])", "vmean([<2026-10-05 Mon>])",
349 "vmean([<2026-10-05 Mon>,<2026-10-06 Tue>,<2026-10-10 Sat>])", "vvar([<2026-10-05 Mon>,<2026-10-07 Wed>])",
350 "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)",
351 "date(2026,2,32)", "date(2026.5,1,1)", "date(2026,1,1,10,30,1.5)", "date([1,2])", "year([1,2])",
352 "newweek(<2026-10-15 Thu>,7)", "newyear(<2026-10-15 Thu>,400)", "incmonth(<2026-10-05 Mon>,1.5)",
353 "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>"] {
247354 #expect(throws: Calc.Unsupported.self, "\(e)") { try Calc.evaluate(e) }
248355 }
249356 var modes = Calc.Modes()
357 // Calc's daylight saving rules aren't reproduced.
358 modes.timeZone = TimeZone(identifier: "America/New_York")!
359 #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("unixtime(<2026-10-05 Mon>)", modes: modes) }
360 #expect(try Calc.evaluate("julian(<2026-10-05 Mon>)", modes: modes) == "2461319")
250361 modes.precision = 15
251362 #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("sinh(1)", modes: modes) }
363 #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("<2026-10-05 Mon 10:00>+1", modes: modes) }
252364 modes.precision = 19
253365 #expect(throws: Calc.Unsupported.self) { try Calc.evaluate("1+1", modes: modes) }
254366 }
Tests/OrgCoreTests/TableFormulaTests.swift +24
@@ -69,6 +69,30 @@ struct TableFormulaTests {
6969 "#+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",
7070 ]
7171
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 |\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",
80 ]
81
82 /// Results that aren't numbers under `N` and the duration flags: `#ERROR`, or for a
83 /// duration an error.
84 static let numericResults = [
85 "| 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",
86 "| a | b |\n|---+---|\n| 1 | |\n#+TBLFM: $2=$1/3;TF\n",
87 "| a | b |\n|---+---|\n| 1 | |\n#+TBLFM: $2=nan;T\n",
88 "| a | b |\n|---+---|\n| <2026-01-01 Thu> | |\n#+TBLFM: $2=<2026-12-25 Fri>-$1;U\n",
89 ]
90
91 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
92 func datesMatchEmacs() throws {
93 try compare(Self.dates + Self.numericResults, fallbacksAllowed: false)
94 }
95
7296 @Test func remoteFindsTablesByIDInOtherFiles() {
7397 let other = "* Elsewhere\n:PROPERTIES:\n:ID: far\n:END:\n| v |\n|---|\n| 7 |\n"
7498 RemoteTables.fileWithID = { $0 == "far" ? other : nil }
docs/manual/guide/10-tables.org +31
@@ -429,6 +429,37 @@ times. A date plus a number is a date, written back as an inactive timestamp:
429429,#+TBLFM: $3=$2-$1::$4=$1+7
430430#+END_SRC
431431
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.
437
438| Function | Result |
439|--------------------------------------------+------------------------------------------------------------------------------------|
440| =year=, =month=, =day= | Parts of the date. |
441| =hour=, =minute=, =second= | Parts of the time, 0 for a date without one. |
442| =weekday= | 0 for Sunday to 6 for Saturday. |
443| =yearday= | Day of the year, 1 for 1 January. |
444| =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. |
445| =date(d)= | The day number of date /d/, or the date of day number /d/. |
446| =now()= | The current date and time. |
447| =incmonth(d, n)=, =incyear(d, n)= | /n/ months or years later (1 by default), on the last day if the month is shorter. |
448| =newmonth(d, n)=, =newyear(d, n)= | Day /n/ of the month or year (1 by default; 0 is the last day). |
449| =newweek(d, w)= | The day on or before /d/ that falls on weekday /w/ (0, Sunday, by default). |
450| =badd(d, n)=, =bsub(d, n)= | /n/ business days later or earlier, skipping Saturdays and Sundays. |
451| =bsub(d1, d2)= | Business days from /d2/ to /d1/. |
452| =julian(d)= | The Julian day number of /d/, or the date of a Julian day number. |
453| =unixtime(d)= | Seconds since 1970-01-01 00:00 UTC, or the date of a number of seconds. |
454
455=julian= of a date with a time and =unixtime= use the local time zone. Emacs applies
456the current year's daylight saving rules to every date, which orgstar doesn't, so in a
457time zone with daylight saving time these need Emacs.
458
459With =N=, =T=, =U= or =t= a timestamp field counts as 0. A result that is a date is
460=#ERROR= with =N=, and with =T=, =U= or =t= it stops the recalculation with the error
461Org gives.
462
432463** Lisp formulas
433464
434465A formula that starts with ='(= is Emacs Lisp. Each reference becomes a Lisp string,
l10n/Localizable.xcstrings +34
@@ -34082,6 +34082,40 @@
3408234082 }
3408334083 }
3408434084 },
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 },
3408534119 "division by zero": {
3408634120 "localizations": {
3408734121 "de": {