Sources/OrgCore/Commands/TimestampCommands.swift

d4c76b8503d7069cc3c2404db3cafc46defe1a9a
orgstar/Sources/OrgCore/Commands/TimestampCommands.swift history · blame · raw

232 lines · 12966 bytes

  1import Foundation
  2
  3extension EmacsBuffer {
  4    /// Reads a date prompt answer the way `org-read-date` does: an empty answer takes the
  5    /// default date.
  6    func readDate(_ answer: String, default defaultDate: Date?) -> ReadDate.Answer {
  7        ReadDate.read(answer, default: defaultDate, now: now, calendar: calendar)
  8    }
  9
 10    /// The date an Org time string stands for, as a prompt default.
 11    func dateDefault(_ stamp: String?) -> Date? { stamp.flatMap(Self.parseTimeString).map(date) }
 12
 13    func date(_ components: DateComponents) -> Date { calendar.date(from: components)! }
 14
 15    /// `org-timestamp`: replaces the timestamp at point, keeping its repeater, or inserts one.
 16    func timestampCommand(_ answer: String, inactive: Bool) {
 17        let existing = atTimestamp()
 18        let stamp = existing.map { substring($0.match[0]!.lowerBound, $0.match[0]!.upperBound) }
 19        let defaultDate = stamp.flatMap(Self.parseTimeString).map(date)
 20        let repeater = stamp.flatMap { $0.firstMatch(of: try! Regex("([.+-]+[0-9]+[hdwmy] ?)+")).map { String($0.output[0].substring!) } }
 21        let result = readDate(answer, default: defaultDate)
 22        let components = result.components(calendar)
 23        if let existing {
 24            replace(existing.match[0]!, with: "")
 25            insertTimestamp(components, withTime: result.timeGiven, inactive: inactive, endTime: result.endTime)
 26            if let repeater {
 27                point -= 1
 28                insert(" " + repeater)
 29            }
 30        } else {
 31            insertTimestamp(components, withTime: result.timeGiven, inactive: inactive, endTime: result.endTime)
 32        }
 33    }
 34
 35    /// The first timestamp after `kind` in the entry, as the date prompt's default.
 36    func planningDefault(_ kind: PlanningKind) -> String? {
 37        saveExcursion {
 38            guard (try? backToHeading()) != nil else { return nil }
 39            let end = saveExcursion { () -> Int in outlineNextHeading(); return point }
 40            return searchForward(kind.pattern, bound: end, caseInsensitive: false).map { substring($0[1]!.lowerBound, $0[1]!.upperBound) }
 41        }
 42    }
 43
 44    /// `org--deadline-or-schedule` without a prefix argument.
 45    func schedule(_ kind: PlanningKind, answer: String, answers: [String: String] = [:]) throws {
 46        let old = planningValue(kind)
 47        let repeatPattern = "([.+-]+[0-9]+[hdwmy](?:[/ ][-+]?[0-9]+[hdwmy])?)"
 48        let repeater = old.flatMap { $0.firstMatch(of: try! Regex(repeatPattern)).map { String($0.output[1].substring!) } }
 49        let defaultDate = planningDefault(kind).flatMap(Self.parseTimeString).map(date)
 50        let result = readDate(answer, default: defaultDate)
 51        try addPlanningInfo(kind, time: result.components(calendar), withTime: result.timeGiven, endTime: result.endTime, remove: [.closed])
 52        if let repeater, let inserted = lastInsertedTimestamp {
 53            try saveExcursion {
 54                try backToHeading()
 55                let bound = saveExcursion { () -> Int in forwardLine(2); return lineEnd(point) }
 56                if let match = searchForward(NSRegularExpression.escapedPattern(for: kind.keyword + " " + inserted), bound: bound, caseInsensitive: false) {
 57                    point = match[0]!.upperBound - 1
 58                    insert(" " + repeater)
 59                }
 60            }
 61        }
 62        if let old, let inserted = lastInsertedTimestamp {
 63            try logPlanningChange(kind, old: "<" + old + ">", new: inserted, answers: answers)
 64        }
 65    }
 66
 67    /// `org--deadline-or-schedule` with C-u: removes the planning timestamp.
 68    func removePlanning(_ kind: PlanningKind) {
 69        guard planningValue(kind) != nil else { return }
 70        saveExcursion {
 71            guard let begin = try? backToHeading() else { return }
 72            outlineNextHeading()
 73            let pattern = "\\b" + NSRegularExpression.escapedPattern(for: kind.keyword) + " +<[^>\\n]+>[ \\t]*"
 74            while let match = searchBackward(pattern, bound: begin, caseInsensitive: false) {
 75                replace(match[0]!, with: "")
 76                let before = substring(lineStart(point), point)
 77                if before.contains(where: { !$0.isWhitespace }), character(at: point - 1) == 32 {
 78                    deleteRegion(point - 1, point)
 79                } else if substring(lineStart(point), lineEnd(point)).allSatisfy({ $0 == " " || $0 == "\t" }) {
 80                    deleteRegion(lineStart(point), min(length, lineEnd(point) + 1))
 81                }
 82            }
 83        }
 84    }
 85}
 86
 87private func timestampCommand(_ context: EditContext, _ body: (EmacsBuffer) throws -> Void) -> CommandStep {
 88    commitBuffer(context, body)
 89}
 90
 91private func atTimestamp(_ context: EditContext) -> Bool {
 92    EmacsBuffer(context.text, point: context.caret).atTimestamp() != nil
 93}
 94
 95/// The prompt's starting text: the time of the timestamp at the caret, as org pre-fills it.
 96private func timeOfDayAtCaret(_ context: EditContext) -> String {
 97    let buffer = EmacsBuffer(context.text, point: context.caret)
 98    guard let match = buffer.atTimestamp()?.match[0] else { return "" }
 99    return EmacsBuffer.compactTimeOfDay(buffer.substring(match.lowerBound, match.upperBound)) ?? ""
100}
101
102/// C-c . and C-c !: `org-timestamp`.
103public struct InsertTimestamp: OrgCommand {
104    let inactive: Bool
105    public init(inactive: Bool = false) { self.inactive = inactive }
106    public var id: String { inactive ? "org.timestamp.inactive" : "org.timestamp.active" }
107    public var title: String { inactive ? "Insert Inactive Timestamp" : "Insert Timestamp" }
108    public func applies(in context: EditContext) -> Bool { true }
109    public func run(in context: EditContext) -> CommandStep {
110        guard let answer = context.answers["date"] else {
111            let buffer = EmacsBuffer(context.text, point: context.caret)
112            buffer.calendar = context.calendar
113            let stamp = buffer.atTimestamp().map { buffer.substring($0.match[0]!.lowerBound, $0.match[0]!.upperBound) }
114            let repeated = context.lastCommand == "org.timestamp.active" || context.lastCommand == "org.timestamp.inactive"
115            return .prompt(Prompt(key: "date", message: "Date+time:", initial: timeOfDayAtCaret(context),
116                                  date: .init(defaultDate: repeated ? nil : buffer.dateDefault(stamp), inactive: inactive)))
117        }
118        // Twice in a row on a timestamp: a range to a second one.
119        let repeated = context.lastCommand == "org.timestamp.active" || context.lastCommand == "org.timestamp.inactive"
120        if repeated, EmacsBuffer(context.text, point: context.caret).atTimestamp() != nil {
121            return timestampCommand(context) { buffer in
122                let result = buffer.readDate(answer, default: nil)
123                buffer.insert("--")
124                buffer.insertTimestamp(result.components(buffer.calendar), withTime: result.timeGiven, inactive: inactive)
125            }
126        }
127        return timestampCommand(context) { $0.timestampCommand(answer, inactive: inactive) }
128    }
129}
130
131/// C-c C-s and C-c C-d: `org-schedule` and `org-deadline`.
132public struct SetPlanning: OrgCommand {
133    let deadline: Bool
134    public init(deadline: Bool) { self.deadline = deadline }
135    public var id: String { deadline ? "org.deadline" : "org.schedule" }
136    public var title: String { deadline ? "Set Deadline" : "Schedule" }
137    public func applies(in context: EditContext) -> Bool { entryHeading(at: context.caret, in: context.tree) != nil }
138    public func run(in context: EditContext) -> CommandStep {
139        guard entryHeading(at: context.caret, in: context.tree) != nil else { return .failed("Before first headline") }
140        let kind: EmacsBuffer.PlanningKind = deadline ? .deadline : .scheduled
141        guard let answer = context.answers["date"] else {
142            let buffer = EmacsBuffer(context.text, point: context.caret)
143            buffer.calendar = context.calendar
144            let initial = buffer.planningDefault(kind).flatMap(EmacsBuffer.compactTimeOfDay) ?? ""
145            return .prompt(Prompt(key: "date", message: deadline ? "DEADLINE:" : "SCHEDULED:", initial: initial,
146                                  date: .init(defaultDate: buffer.dateDefault(buffer.planningDefault(kind)))))
147        }
148        return timestampCommand(context) { try $0.schedule(kind, answer: answer, answers: context.answers) }
149    }
150}
151
152/// C-u C-c C-s and C-u C-c C-d.
153public struct RemovePlanning: OrgCommand {
154    let deadline: Bool
155    public init(deadline: Bool) { self.deadline = deadline }
156    public var id: String { deadline ? "org.deadline.remove" : "org.schedule.remove" }
157    public var title: String { deadline ? "Remove Deadline" : "Remove Schedule" }
158    public func applies(in context: EditContext) -> Bool { entryHeading(at: context.caret, in: context.tree) != nil }
159    public func run(in context: EditContext) -> CommandStep {
160        timestampCommand(context) { buffer in
161            let kind: EmacsBuffer.PlanningKind = deadline ? .deadline : .scheduled
162            let old = buffer.planningValue(kind)
163            if let old { try buffer.logPlanningChange(kind, old: "<" + old + ">", new: nil, answers: context.answers) }
164            buffer.removePlanning(kind)
165        }
166    }
167}
168
169/// S-up and S-down on a timestamp: `org-timestamp-up` and `org-timestamp-down`.
170public struct ShiftTimestamp: OrgCommand {
171    let up: Bool
172    public init(up: Bool) { self.up = up }
173    public var id: String { up ? "org.timestamp.up" : "org.timestamp.down" }
174    public var title: String { up ? "Increase Timestamp Part" : "Decrease Timestamp Part" }
175    public func applies(in context: EditContext) -> Bool { atTimestamp(context) }
176    public func run(in context: EditContext) -> CommandStep {
177        timestampCommand(context) { try $0.changeTimestamp(up ? 1 : -1, updown: true) }
178    }
179}
180
181/// S-right and S-left on a timestamp: `org-timestamp-up-day` and `org-timestamp-down-day`.
182public struct ShiftTimestampDay: OrgCommand {
183    let later: Bool
184    public init(later: Bool) { self.later = later }
185    public var id: String { later ? "org.timestamp.day-later" : "org.timestamp.day-earlier" }
186    public var title: String { later ? "Timestamp One Day Later" : "Timestamp One Day Earlier" }
187    public func applies(in context: EditContext) -> Bool { atTimestamp(context) }
188    public func run(in context: EditContext) -> CommandStep {
189        timestampCommand(context) { try $0.changeTimestamp(later ? 1 : -1, what: .day, updown: true) }
190    }
191}
192
193/// C-c C-y: `org-evaluate-time-range`. On a clock line, updates it; otherwise says how long the
194/// range at the caret, or the first on its line, lasts.
195public struct EvaluateTimeRange: OrgCommand {
196    public init() {}
197    public var id: String { "org.timestamp.evaluate-range" }
198    public var title: String { "Evaluate Time Range" }
199    public func applies(in context: EditContext) -> Bool { true }
200    public func run(in context: EditContext) -> CommandStep {
201        let buffer = EmacsBuffer(context.text, point: context.caret)
202        buffer.calendar = context.calendar
203        if buffer.lookingAtLine("^[ \\t]*CLOCK:") { return CtrlCCtrlC().run(in: context) }
204        let ns = context.text as NSString
205        let line = ns.lineRange(for: NSRange(location: min(context.caret, ns.length), length: 0))
206        let regex = try! NSRegularExpression(pattern: "[\\[<]([0-9]{4}-[0-9]{2}-[0-9]{2}[^\\]>\\n]*?)[\\]>]--?-?[\\[<]([0-9]{4}-[0-9]{2}-[0-9]{2}[^\\]>\\n]*?)[\\]>]")
207        let matches = regex.matches(in: context.text, range: line)
208        guard let m = matches.first(where: { $0.range.location <= context.caret && context.caret <= NSMaxRange($0.range) }) ?? matches.first else {
209            return .failed("Not at a timestamp range, and none found in current line")
210        }
211        let ts1 = ns.substring(with: m.range(at: 1))
212        let ts2 = ns.substring(with: m.range(at: 2))
213        let haveTime = ts1.count > 15 || ts2.count > 15
214        let t1 = TagsMatcher.seconds(ts1, now: context.now, calendar: context.calendar)
215        let t2 = TagsMatcher.seconds(ts2, now: context.now, calendar: context.calendar)
216        var diff = abs(t2 - t1)
217        var d = 0, h = 0, minutes = 0
218        if haveTime {
219            d = Int(floor(diff / 86400)); diff = diff.truncatingRemainder(dividingBy: 86400)
220            h = Int(floor(diff / 3600)); diff = diff.truncatingRemainder(dividingBy: 3600)
221            minutes = Int(floor(diff / 60))
222        } else {
223            d = Int((diff / 86400).rounded())
224        }
225        var parts: [String] = []
226        if d > 0 { parts.append("\(d) day" + (d > 1 ? "s" : "")) }
227        if h > 0 { parts.append("\(h) hour" + (h > 1 ? "s" : "")) }
228        if minutes > 0 { parts.append("\(minutes) minute" + (minutes > 1 ? "s" : "")) }
229        let text = parts.isEmpty ? "" : parts.joined(separator: " ") + " "
230        return .commit(EditResult(baseRevision: context.revision, edits: [], effects: [.message(text)]))
231    }
232}