Sources/OrgCore/Agenda/Days.swift

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

154 lines · 7382 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    /// The day on or before `absolute` that falls on `weekday` (0 is Sunday), as
 40    /// `org-agenda-start-on-weekday` starts a week; nil keeps `absolute`.
 41    public static func weekStart(_ absolute: Int, on weekday: Int?) -> Int {
 42        guard let weekday else { return absolute }
 43        let d = self.weekday(absolute) - weekday
 44        return absolute - (d < 0 ? d + 7 : d)
 45    }
 46
 47    /// `org-days-to-iso-week`.
 48    public static func isoWeek(_ absolute: Int) -> Int {
 49        let monday = absolute - (weekday(absolute) + 6) % 7
 50        let thursday = monday + 3
 51        let year = date(thursday).year
 52        return (thursday - Days.absolute(year: year, month: 1, day: 1)) / 7 + 1
 53    }
 54
 55    /// The day of a `Date` in `calendar`'s time zone.
 56    public static func absolute(_ date: Date, calendar: Calendar) -> Int {
 57        let c = calendar.dateComponents([.year, .month, .day], from: date)
 58        return absolute(year: c.year!, month: c.month!, day: c.day!)
 59    }
 60
 61    static let dateRegex = try! NSRegularExpression(pattern: "([0-9]{4})-([0-9]{2})-([0-9]{2})")
 62    static let timeRegex = try! NSRegularExpression(pattern: "([0-9]{1,2}):([0-9]{2})")
 63
 64    /// `time-to-days` of `org-time-string-to-time`: the first date in the string.
 65    static func absolute(of string: String) -> Int? {
 66        let ns = string as NSString
 67        guard let m = dateRegex.firstMatch(in: string, range: NSRange(location: 0, length: ns.length)) else { return nil }
 68        func int(_ i: Int) -> Int { Int(ns.substring(with: m.range(at: i)))! }
 69        return absolute(year: int(1), month: int(2), day: int(3))
 70    }
 71
 72    /// The hour of `org-parse-time-string`, 0 when there is none.
 73    static func hour(of string: String) -> Int {
 74        let ns = string as NSString
 75        guard let date = dateRegex.firstMatch(in: string, range: NSRange(location: 0, length: ns.length)) else { return 0 }
 76        let rest = NSRange(location: NSMaxRange(date.range), length: ns.length - NSMaxRange(date.range))
 77        // org-ts-regexp0: a day name may sit between the date and the time.
 78        let pattern = Self.hourRegex
 79        guard let m = pattern.firstMatch(in: string, range: rest) else { return 0 }
 80        return Int(ns.substring(with: m.range(at: 3)))!
 81    }
 82
 83    public enum Prefer { case past, future, nearest }
 84
 85    static let repeatRegex = try! NSRegularExpression(pattern: "\\+([0-9]+)([hdwmy])")
 86
 87    /// `org-closest-date`: the occurrence of a repeating timestamp `start` closest to `current`.
 88    /// Timestamps without a repeater give their own day.
 89    static func closest(_ start: String, to current: Int, prefer: Prefer) -> Int? {
 90        guard let sday = absolute(of: start) else { return nil }
 91        let ns = start as NSString
 92        guard let m = repeatRegex.firstMatch(in: start, range: NSRange(location: 0, length: ns.length)) else { return sday }
 93        let value = Int(ns.substring(with: m.range(at: 1)))!
 94        let unit = ns.substring(with: m.range(at: 2))
 95        if value == 0 { return sday }
 96        let cday = current
 97        if cday <= sday { return sday }
 98        let base = date(sday)
 99        let target = date(cday)
100        var n1: Int
101        var n2: Int
102        switch unit {
103        case "h":
104            let missing = mod(24 * (cday - sday) - hour(of: start), value)
105            n1 = missing == 0 ? cday : cday - (1 + missing / 24)
106            n2 = cday + (value - missing) / 24
107        case "d", "w":
108            let step = unit == "w" ? 7 * value : value
109            n1 = sday + step * ((cday - sday) / step)
110            n2 = n1 + step
111        case "m":
112            func add(_ d: (year: Int, month: Int, day: Int), _ n: Int) -> (year: Int, month: Int, day: Int) {
113                (d.year, d.month + n, d.day)
114            }
115            let months = ((12 * (target.year - base.year) + (target.month - base.month) + (target.day > base.day ? 0 : -1)) / value) * value
116            let before = add(base, months)
117            n1 = absolute(year: before.year, month: before.month, day: before.day)
118            let after = add(before, value)
119            n2 = absolute(year: after.year, month: after.month, day: after.day)
120        default:
121            let later = target.month > base.month || (target.month == base.month && target.day > base.day)
122            let years = ((target.year - base.year - (later ? 0 : 1)) / value) * value
123            n1 = absolute(year: base.year + years, month: base.month, day: base.day)
124            n2 = absolute(year: base.year + years + value, month: base.month, day: base.day)
125        }
126        switch prefer {
127        case .past: return cday == n2 ? n2 : n1
128        case .future: return cday == n1 ? n1 : n2
129        case .nearest: return abs(cday - n1) > abs(cday - n2) ? n2 : n1
130        }
131    }
132
133    private static func mod(_ a: Int, _ b: Int) -> Int { ((a % b) + b) % b }
134
135    static let wdaysRegex = try! NSRegularExpression(pattern: "-([0-9]+)([hdwmy])(\\z|>| )")
136
137    /// `org-get-wdays`: the warning days of a deadline, or with `delay` the delay days of a
138    /// scheduled timestamp.
139    static func warningDays(_ stamp: String, delay: Bool, defaultDays: Int) -> Int {
140        let tv = defaultDays
141        if (delay && tv < 0) || (!delay && tv <= 0) { return -tv }
142        let ns = stamp as NSString
143        guard let m = wdaysRegex.firstMatch(in: stamp, range: NSRange(location: 0, length: ns.length)) else { return tv }
144        let n = Double(ns.substring(with: m.range(at: 1)))!
145        let factor: Double = switch ns.substring(with: m.range(at: 2)) {
146        case "d": 1
147        case "w": 7
148        case "m": 30.4
149        case "y": 365.25
150        default: 0.041667
151        }
152        return Int((n * factor).rounded(.down))
153    }
154}