Sources/OrgCore/Agenda/Days.swift

cba778d55e19c2c7a8dce862eb5d5f46d3d8c792
orgstar/Sources/OrgCore/Agenda/Days.swift history · blame · raw

146 lines · 6995 bytes

  1import Foundation
  2
  3/// Calendar days as Emacs numbers them (`calendar-absolute-from-gregorian`): 1 is
  4/// 1 January of year 1, proleptic Gregorian.
  5public enum Days {
  6    static let hourRegex = try! NSRegularExpression(pattern: "^( +[^\\]+0-9>\\r\\n -]+)?( +([0-9]{1,2}):([0-9]{2}))")
  7
  8    /// Out-of-range days and months roll over, as with `encode-time`.
  9    public static func absolute(year: Int, month: Int, day: Int) -> Int {
 10        let monthIndex = month - 1
 11        let y = year + Int((Double(monthIndex) / 12).rounded(.down))
 12        let m = monthIndex - 12 * Int((Double(monthIndex) / 12).rounded(.down)) + 1
 13        // Days from civil (Howard Hinnant), with 1970-01-01 = 0.
 14        let yy = m <= 2 ? y - 1 : y
 15        let era = (yy >= 0 ? yy : yy - 399) / 400
 16        let yoe = yy - era * 400
 17        let doy = (153 * (m > 2 ? m - 3 : m + 9) + 2) / 5
 18        let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy
 19        return era * 146097 + doe - 719468 + 719163 + day - 1
 20    }
 21
 22    public static func date(_ absolute: Int) -> (year: Int, month: Int, day: Int) {
 23        let z = absolute - 719163 + 719468
 24        let era = (z >= 0 ? z : z - 146096) / 146097
 25        let doe = z - era * 146097
 26        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365
 27        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100)
 28        let mp = (5 * doy + 2) / 153
 29        let day = doy - (153 * mp + 2) / 5 + 1
 30        let month = mp < 10 ? mp + 3 : mp - 9
 31        return (yoe + era * 400 + (month <= 2 ? 1 : 0), month, day)
 32    }
 33
 34    /// 0 is Sunday, as `calendar-day-of-week`.
 35    public static func weekday(_ absolute: Int) -> Int {
 36        ((absolute % 7) + 7) % 7
 37    }
 38
 39    /// `org-days-to-iso-week`.
 40    public static func isoWeek(_ absolute: Int) -> Int {
 41        let monday = absolute - (weekday(absolute) + 6) % 7
 42        let thursday = monday + 3
 43        let year = date(thursday).year
 44        return (thursday - Days.absolute(year: year, month: 1, day: 1)) / 7 + 1
 45    }
 46
 47    /// The day of a `Date` in `calendar`'s time zone.
 48    public static func absolute(_ date: Date, calendar: Calendar) -> Int {
 49        let c = calendar.dateComponents([.year, .month, .day], from: date)
 50        return absolute(year: c.year!, month: c.month!, day: c.day!)
 51    }
 52
 53    static let dateRegex = try! NSRegularExpression(pattern: "([0-9]{4})-([0-9]{2})-([0-9]{2})")
 54    static let timeRegex = try! NSRegularExpression(pattern: "([0-9]{1,2}):([0-9]{2})")
 55
 56    /// `time-to-days` of `org-time-string-to-time`: the first date in the string.
 57    static func absolute(of string: String) -> Int? {
 58        let ns = string as NSString
 59        guard let m = dateRegex.firstMatch(in: string, range: NSRange(location: 0, length: ns.length)) else { return nil }
 60        func int(_ i: Int) -> Int { Int(ns.substring(with: m.range(at: i)))! }
 61        return absolute(year: int(1), month: int(2), day: int(3))
 62    }
 63
 64    /// The hour of `org-parse-time-string`, 0 when there is none.
 65    static func hour(of string: String) -> Int {
 66        let ns = string as NSString
 67        guard let date = dateRegex.firstMatch(in: string, range: NSRange(location: 0, length: ns.length)) else { return 0 }
 68        let rest = NSRange(location: NSMaxRange(date.range), length: ns.length - NSMaxRange(date.range))
 69        // org-ts-regexp0: a day name may sit between the date and the time.
 70        let pattern = Self.hourRegex
 71        guard let m = pattern.firstMatch(in: string, range: rest) else { return 0 }
 72        return Int(ns.substring(with: m.range(at: 3)))!
 73    }
 74
 75    public enum Prefer { case past, future, nearest }
 76
 77    static let repeatRegex = try! NSRegularExpression(pattern: "\\+([0-9]+)([hdwmy])")
 78
 79    /// `org-closest-date`: the occurrence of a repeating timestamp `start` closest to `current`.
 80    /// Timestamps without a repeater give their own day.
 81    static func closest(_ start: String, to current: Int, prefer: Prefer) -> Int? {
 82        guard let sday = absolute(of: start) else { return nil }
 83        let ns = start as NSString
 84        guard let m = repeatRegex.firstMatch(in: start, range: NSRange(location: 0, length: ns.length)) else { return sday }
 85        let value = Int(ns.substring(with: m.range(at: 1)))!
 86        let unit = ns.substring(with: m.range(at: 2))
 87        if value == 0 { return sday }
 88        let cday = current
 89        if cday <= sday { return sday }
 90        let base = date(sday)
 91        let target = date(cday)
 92        var n1: Int
 93        var n2: Int
 94        switch unit {
 95        case "h":
 96            let missing = mod(24 * (cday - sday) - hour(of: start), value)
 97            n1 = missing == 0 ? cday : cday - (1 + missing / 24)
 98            n2 = cday + (value - missing) / 24
 99        case "d", "w":
100            let step = unit == "w" ? 7 * value : value
101            n1 = sday + step * ((cday - sday) / step)
102            n2 = n1 + step
103        case "m":
104            func add(_ d: (year: Int, month: Int, day: Int), _ n: Int) -> (year: Int, month: Int, day: Int) {
105                (d.year, d.month + n, d.day)
106            }
107            let months = ((12 * (target.year - base.year) + (target.month - base.month) + (target.day > base.day ? 0 : -1)) / value) * value
108            let before = add(base, months)
109            n1 = absolute(year: before.year, month: before.month, day: before.day)
110            let after = add(before, value)
111            n2 = absolute(year: after.year, month: after.month, day: after.day)
112        default:
113            let later = target.month > base.month || (target.month == base.month && target.day > base.day)
114            let years = ((target.year - base.year - (later ? 0 : 1)) / value) * value
115            n1 = absolute(year: base.year + years, month: base.month, day: base.day)
116            n2 = absolute(year: base.year + years + value, month: base.month, day: base.day)
117        }
118        switch prefer {
119        case .past: return cday == n2 ? n2 : n1
120        case .future: return cday == n1 ? n1 : n2
121        case .nearest: return abs(cday - n1) > abs(cday - n2) ? n2 : n1
122        }
123    }
124
125    private static func mod(_ a: Int, _ b: Int) -> Int { ((a % b) + b) % b }
126
127    static let wdaysRegex = try! NSRegularExpression(pattern: "-([0-9]+)([hdwmy])(\\z|>| )")
128
129    /// `org-get-wdays`: the warning days of a deadline, or with `delay` the delay days of a
130    /// scheduled timestamp.
131    static func warningDays(_ stamp: String, delay: Bool, defaultDays: Int) -> Int {
132        let tv = defaultDays
133        if (delay && tv < 0) || (!delay && tv <= 0) { return -tv }
134        let ns = stamp as NSString
135        guard let m = wdaysRegex.firstMatch(in: stamp, range: NSRange(location: 0, length: ns.length)) else { return tv }
136        let n = Double(ns.substring(with: m.range(at: 1)))!
137        let factor: Double = switch ns.substring(with: m.range(at: 2)) {
138        case "d": 1
139        case "w": 7
140        case "m": 30.4
141        case "y": 365.25
142        default: 0.041667
143        }
144        return Int((n * factor).rounded(.down))
145    }
146}