Sources/OrgCore/Capture/Datetree.swift

06941b2cf25c6ccc1629723cd7951910ce15e67a
orgstar/Sources/OrgCore/Capture/Datetree.swift history · blame · raw

164 lines · 8688 bytes

  1import Foundation
  2
  3// Date trees (org-datetree.el, Org 9.8.7): `org-datetree-find-create-entry` with the groupings
  4// capture uses, and `org-datetree-add-timestamp` nil. Each level is found or created inside
  5// the one above it, as org does while narrowed to it.
  6enum Datetree {
  7    static let weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
  8    static let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
  9
 10    /// Each level's heading title, and the pattern whose first group orders siblings. With
 11    /// weeks, the year and month are those of the ISO week's Thursday; with weeks but no
 12    /// months, quarters are 13 weeks.
 13    static func levels(_ tree: CaptureTemplate.TreeType, date: DateComponents) -> [(title: String, pattern: String)] {
 14        var gregorian = Calendar(identifier: .gregorian)
 15        gregorian.timeZone = TimeZone(identifier: "UTC")!
 16        let day = gregorian.date(from: DateComponents(year: date.year, month: date.month, day: date.day))!
 17        let weekdayIndex = gregorian.component(.weekday, from: day) - 1
 18        var iso = Calendar(identifier: .iso8601)
 19        iso.timeZone = gregorian.timeZone
 20        let isoYear = iso.component(.yearForWeekOfYear, from: day)
 21        let week = iso.component(.weekOfYear, from: day)
 22        let groups = tree.groups
 23        let weeks = groups.contains(.week)
 24        let year = weeks ? isoYear : date.year!
 25        let thursday = gregorian.date(byAdding: .day, value: 4 - (weekdayIndex == 0 ? 7 : weekdayIndex), to: day)!
 26        let month = weeks ? gregorian.component(.month, from: thursday) : date.month!
 27        let quarter = weeks && !groups.contains(.month) ? min(4, 1 + (week - 1) / 13) : 1 + (month - 1) / 3
 28        var levels: [(title: String, pattern: String)] = []
 29        if groups.contains(.year) { levels.append((String(year), "([12][0-9]{3})")) }
 30        if groups.contains(.quarter) { levels.append(("\(year)-Q\(quarter)", "([12][0-9]{3}-Q[1-4])")) }
 31        if groups.contains(.month) {
 32            levels.append((String(format: "%04d-%02d ", year, month) + months[month - 1], "([12][0-9]{3}-[01][0-9]) \\w+"))
 33        }
 34        if weeks { levels.append((String(format: "%04d-W%02d", isoYear, week), "([12][0-9]{3}-W[0-5][0-9])")) }
 35        if groups.contains(.day) {
 36            levels.append((String(format: "%04d-%02d-%02d ", date.year!, date.month!, date.day!) + weekdays[weekdayIndex],
 37                           "([12][0-9]{3}-[01][0-9]-[0123][0-9]) \\w+"))
 38        }
 39        return levels
 40    }
 41
 42    /// Point at the date's entry, created where missing, under the heading at `parent` or at
 43    /// the top of the file. Returns the entry's start.
 44    static func findCreate(_ buffer: EmacsBuffer, under parent: Int?, tree: CaptureTemplate.TreeType, date: DateComponents) -> Int {
 45        let low = buffer.marker(parent ?? 0)
 46        let high = buffer.marker(parent.map { narrowEnd(buffer, $0, limit: buffer.length) } ?? buffer.length, advances: true)
 47        defer {
 48            buffer.release(low)
 49            buffer.release(high)
 50        }
 51        var level = parent.map { Capture.headingLevel(buffer, at: $0) + 1 } ?? 1
 52        for (title, pattern) in levels(tree, date: date) {
 53            subheading(buffer, title: title, pattern: pattern, level: level, low: low, high: high)
 54            level += 1
 55        }
 56        return low.position
 57    }
 58
 59    /// `org-datetree--find-create-subheading`: leaves the region narrowed to the subheading.
 60    static func subheading(_ buffer: EmacsBuffer, title: String, pattern: String, level: Int, low: EmacsBuffer.Marker, high: EmacsBuffer.Marker) {
 61        func compare(_ sibling: String) -> Int? {
 62            guard let a = firstGroup(pattern, sibling), let b = firstGroup(pattern, title) else { return nil }
 63            return a < b ? -1 : a > b ? 1 : 0
 64        }
 65        var sibling: (start: Int, order: Int)?
 66        buffer.point = low.position
 67        while let match = buffer.searchForward("^(\\*+) ", bound: high.position, caseInsensitive: false) {
 68            let start = match[0]!.lowerBound
 69            buffer.point = buffer.lineEnd(start)
 70            guard match[1]!.count == level else { continue }
 71            if let order = compare(rawTitle(buffer, start)), order >= 0 {
 72                sibling = (start, order)
 73                break
 74            }
 75        }
 76        if let sibling {
 77            buffer.point = sibling.start
 78        } else {
 79            buffer.point = high.position
 80            if !buffer.bolp { buffer.insert("\n") }
 81        }
 82        if let sibling, sibling.order == 0 {
 83            narrow(buffer, to: sibling.start, low: low, high: high)
 84            return
 85        }
 86        let end = buffer.point
 87        while buffer.point > low.position, let c = buffer.character(at: buffer.point - 1), c == 32 || c == 9 || c == 10 { buffer.point -= 1 }
 88        buffer.deleteRegion(buffer.point, end)
 89        if blankBeforeHeading(buffer, low: low.position, high: high.position) { buffer.insert("\n") }
 90        buffer.insert("\n" + String(repeating: "*", count: level) + " " + title + "\n")
 91        buffer.forwardLine(-1)
 92        narrow(buffer, to: buffer.point, low: low, high: high)
 93    }
 94
 95    static func firstGroup(_ pattern: String, _ s: String) -> String? {
 96        let regex = try! NSRegularExpression(pattern: pattern)
 97        let ns = s as NSString
 98        guard let m = regex.firstMatch(in: s, range: NSRange(location: 0, length: ns.length)) else { return nil }
 99        return ns.substring(with: m.range(at: 1))
100    }
101
102    /// A heading's `:raw-value`: its title without keyword, priority or tags.
103    static func rawTitle(_ buffer: EmacsBuffer, _ start: Int) -> String {
104        buffer.saveExcursion {
105            buffer.point = start
106            guard let match = buffer.lookingAt(buffer.complexHeadingPattern), let title = match[4] else { return "" }
107            return buffer.substring(title.lowerBound, title.upperBound)
108        }
109    }
110
111    /// `org-narrow-to-subtree` inside the current region.
112    static func narrow(_ buffer: EmacsBuffer, to heading: Int, low: EmacsBuffer.Marker, high: EmacsBuffer.Marker) {
113        low.position = heading
114        high.position = narrowEnd(buffer, heading, limit: high.position)
115        buffer.point = heading
116    }
117
118    /// The subtree's end, before the newline that precedes the next heading, within `limit`.
119    static func narrowEnd(_ buffer: EmacsBuffer, _ heading: Int, limit: Int) -> Int {
120        let end = buffer.saveExcursion { () -> Int in
121            Capture.endOfSubtree(buffer, heading: heading)
122            return buffer.point
123        }
124        return min(limit, end == buffer.length ? end : end - 1)
125    }
126
127    /// `org--blank-before-heading-p` with `org-blank-before-new-entry` `(heading . auto)`,
128    /// in the region `low..<high`.
129    static func blankBeforeHeading(_ buffer: EmacsBuffer, low: Int, high: Int) -> Bool {
130        buffer.saveExcursion {
131            func headingStart(before limit: Int) -> Int? {
132                buffer.saveExcursion {
133                    buffer.point = buffer.lineEnd(limit)
134                    return buffer.searchBackward("^\\*+ ", bound: low, caseInsensitive: false)?[0]?.lowerBound
135                }
136            }
137            /// `outline-next-heading` bounded by `high`.
138            func nextHeading() -> Bool {
139                if let match = buffer.searchForward("\\n\\*+ ", bound: high, caseInsensitive: false) {
140                    buffer.point = match[0]!.lowerBound + 1
141                    return true
142                }
143                buffer.point = high
144                return false
145            }
146            func previousLineEmpty() -> Bool {
147                guard buffer.point > low else { return false }
148                let start = buffer.lineStart(buffer.point)
149                guard start > low else { return false }
150                let previous = max(low, buffer.lineStart(start - 1))
151                return buffer.substring(previous, start - 1).allSatisfy { $0 == " " || $0 == "\t" }
152            }
153            if headingStart(before: buffer.point) == nil {
154                guard nextHeading() else { return false }
155            }
156            guard let heading = headingStart(before: buffer.point) else { return false }
157            buffer.point = heading
158            if buffer.point != low { return previousLineEmpty() }
159            if nextHeading() { return previousLineEmpty() }
160            while buffer.point > low, let c = buffer.character(at: buffer.point - 1), c == 32 || c == 9 { buffer.point -= 1 }
161            return buffer.bolp ? previousLineEmpty() : false
162        }
163    }
164}