Sources/OrgCore/Commands/Timer.swift

343 lines · 17438 bytes

39 symbols in this file
  1import Foundation
  2
  3/// org-timer (org-timer.el, Org 9.8.7): a relative timer counting up from a start time, or a
  4/// countdown counting down to one. The app keeps the timer and gives it to commands in
  5/// `EditingOptions.timer`; commands that change it return `Effect.timer`.
  6public struct OrgTimer: Sendable, Equatable, Codable {
  7    /// `org-timer-start-time`: when a relative timer read 0:00:00, or when a countdown ends.
  8    public var start: Date
  9    /// `org-timer-pause-time`.
 10    public var paused: Date?
 11    /// A countdown rather than a relative timer.
 12    public var isCountdown: Bool
 13    /// A countdown's title (`org-timer-countdown-timer-title`): its heading, or nil.
 14    public var title: String?
 15
 16    public init(start: Date, paused: Date? = nil, isCountdown: Bool = false, title: String? = nil) {
 17        self.start = start
 18        self.paused = paused
 19        self.isCountdown = isCountdown
 20        self.title = title
 21    }
 22
 23    /// The timer's seconds: counted up, or left for a countdown.
 24    public func seconds(now: Date) -> Int {
 25        let time = (paused ?? now).timeIntervalSince1970 - start.timeIntervalSince1970
 26        return abs(Int((isCountdown ? -time : time).rounded(.down)))
 27    }
 28
 29    /// `org-timer-value-string`.
 30    public func value(now: Date, format: String = "%s ") -> String {
 31        format.replacingOccurrences(of: "%s", with: Self.hms(seconds(now: now)))
 32    }
 33
 34    /// The mode line's ` <0:01:23>`.
 35    public func modeLine(now: Date, format: String = "%s ") -> String {
 36        " <" + String(value(now: now, format: format).dropLast()) + ">"
 37    }
 38
 39    /// The countdown's notification text when it ends.
 40    public var doneMessage: String { "\(title ?? "nil"): time out" }
 41
 42    /// `org-timer-secs-to-hms`.
 43    public static func hms(_ seconds: Int) -> String {
 44        let sign = seconds < 0 ? "-" : ""
 45        let s = abs(seconds)
 46        return String(format: "%@%d:%02d:%02d", sign, s / 3600, s / 60 % 60, s % 60)
 47    }
 48
 49    /// `org-timer-hms-to-secs`: 0 when it isn't h:mm:ss.
 50    public static func seconds(_ hms: String) -> Int {
 51        guard let m = hms.firstMatch(of: /([-+]?[0-9]+):([0-9]{2}):([0-9]{2})/) else { return 0 }
 52        let total = abs(Int(m.1)!) * 3600 + Int(m.2)! * 60 + Int(m.3)!
 53        return m.1.hasPrefix("-") ? -total : total
 54    }
 55
 56    /// `org-timer-fix-incomplete`: `5` is 0:00:05 and `2:30` is 0:02:30.
 57    public static func fixIncomplete(_ hms: String) -> String? {
 58        guard let m = hms.firstMatch(of: /(?:([0-9]+:)?([0-9]+:))?([0-9]+)/) else { return nil }
 59        let h = m.1.map { Int($0.dropLast())! } ?? 0
 60        let mm = m.2.map { Int($0.dropLast())! } ?? 0
 61        let replaced = String(format: "%d:%02d:%02d", h, mm, Int(m.3)!)
 62        return hms.replacingCharacters(in: m.range, with: replaced)
 63    }
 64}
 65
 66extension Effect {
 67    static func timerMessage(_ timer: OrgTimer?, _ message: String) -> [Effect] { [.timer(timer), .message(message)] }
 68}
 69
 70/// The timer the context's options hold.
 71private func timer(_ context: EditContext) -> OrgTimer? { context.options.timer }
 72
 73private func effects(_ context: EditContext, _ effects: [Effect]) -> CommandStep {
 74    .commit(EditResult(baseRevision: context.revision, edits: [], effects: effects))
 75}
 76
 77/// C-c C-x 0: `org-timer-start`, from 0:00:00, or with `offset` (C-u C-c C-x 0) from an
 78/// offset asked for, defaulting to a timer stamp at point.
 79public struct TimerStart: OrgCommand {
 80    public let offset: Bool
 81    public init(offset: Bool = false) { self.offset = offset }
 82    public var id: String { offset ? "org.timer.start-offset" : "org.timer.start" }
 83    public var title: String { offset ? "Start Timer with Offset…" : "Start Timer" }
 84    public func applies(in context: EditContext) -> Bool { true }
 85
 86    public func run(in context: EditContext) -> CommandStep {
 87        if timer(context)?.isCountdown == true { return .failed("Countdown timer is running.  Cancel first") }
 88        var delta = 0
 89        if offset {
 90            let line = (context.text as NSString).lineRange(for: NSRange(location: min(context.caret, (context.text as NSString).length), length: 0))
 91            let lineText = (context.text as NSString).substring(with: line)
 92            let caretInLine = context.caret - line.location
 93            let atPoint = lineText.matches(of: /([-+]?[0-9]+):([0-9]{2}):([0-9]{2})/).first { m in
 94                let start = lineText.utf16.distance(from: lineText.startIndex, to: m.range.lowerBound)
 95                let end = lineText.utf16.distance(from: lineText.startIndex, to: m.range.upperBound)
 96                return start <= caretInLine && caretInLine <= end
 97            }.map { String(lineText[$0.range]) }
 98            let def = atPoint ?? "0:00:00"
 99            guard let answer = context.answers["offset"] else {
100                return .prompt(Prompt(key: "offset", message: "Restart timer with offset [\(def)]: ", requireMatch: false))
101            }
102            let typed = answer.contains(where: { !$0.isWhitespace }) ? answer : def
103            guard let fixed = OrgTimer.fixIncomplete(typed) else { return .failed("Cannot parse HMS string \"\(typed)\"") }
104            delta = OrgTimer.seconds(fixed)
105        }
106        let start = context.now.addingTimeInterval(-Double(delta))
107        return effects(context, Effect.timerMessage(OrgTimer(start: start), Self.message(start, delta, context)))
108    }
109
110    /// What `org-timer-start` says.
111    static func message(_ start: Date, _ delta: Int, _ context: EditContext) -> String {
112        let clock = DateFormatter()
113        clock.dateFormat = "HH:mm:ss"
114        clock.timeZone = context.calendar.timeZone
115        return "Timer start time set to \(clock.string(from: start)), current value is \(OrgTimer.hms(delta))"
116    }
117}
118
119/// C-c C-x ,: `org-timer-pause-or-continue`.
120public struct TimerPauseOrContinue: OrgCommand {
121    public init() {}
122    public var id: String { "org.timer.pause" }
123    public var title: String { "Pause or Continue Timer" }
124    public func applies(in context: EditContext) -> Bool { true }
125
126    public func run(in context: EditContext) -> CommandStep {
127        guard var current = timer(context) else { return .failed("No timer is running") }
128        let format = context.options.timerFormat
129        if let paused = current.paused {
130            let elapsed = paused.timeIntervalSince(current.start)
131            // A countdown runs again for what was left; a relative timer goes on from its value.
132            current.start = context.now.addingTimeInterval(-elapsed)
133            current.paused = nil
134            return effects(context, Effect.timerMessage(current, "Timer continues at \(current.value(now: context.now, format: format))"))
135        }
136        current.paused = context.now
137        return effects(context, Effect.timerMessage(current, "Timer paused at \(current.value(now: context.now, format: format))"))
138    }
139}
140
141/// C-c C-x _: `org-timer-stop`.
142public struct TimerStop: OrgCommand {
143    public init() {}
144    public var id: String { "org.timer.stop" }
145    public var title: String { "Stop Timer" }
146    public func applies(in context: EditContext) -> Bool { true }
147
148    public func run(in context: EditContext) -> CommandStep {
149        guard timer(context) != nil else { return .failed("No timer running") }
150        return effects(context, Effect.timerMessage(nil, "Timer stopped"))
151    }
152}
153
154/// C-c C-x .: `org-timer`, the timer's value at point, starting a relative timer first when
155/// none is running.
156public struct InsertTimer: OrgCommand {
157    public init() {}
158    public var id: String { "org.timer.insert" }
159    public var title: String { "Insert Timer Value" }
160    public func applies(in context: EditContext) -> Bool { true }
161
162    public func run(in context: EditContext) -> CommandStep {
163        let (current, started) = Self.timer(context)
164        let value = current.value(now: context.now, format: context.options.timerFormat)
165        let end = context.caret + (value as NSString).length
166        return .commit(EditResult(baseRevision: context.revision, edits: [TextEdit(range: context.caret..<context.caret, replacement: value)],
167                                  selection: [end..<end], effects: started ? Self.started(current, context) : []))
168    }
169
170    static func started(_ timer: OrgTimer, _ context: EditContext) -> [Effect] {
171        Effect.timerMessage(timer, TimerStart.message(timer.start, 0, context))
172    }
173
174    /// The running timer, or a new one started now.
175    static func timer(_ context: EditContext) -> (OrgTimer, started: Bool) {
176        if let current = context.options.timer { return (current, false) }
177        return (OrgTimer(start: context.now), true)
178    }
179}
180
181/// C-c C-x -: `org-timer-item`, a description item with the timer's value: a new item in a
182/// timer list, or a new list.
183public struct InsertTimerItem: OrgCommand {
184    public init() {}
185    public var id: String { "org.timer.item" }
186    public var title: String { "Insert Timer Item" }
187    public func applies(in context: EditContext) -> Bool { true }
188
189    public func run(in context: EditContext) -> CommandStep {
190        let (current, started) = InsertTimer.timer(context)
191        let value = current.value(now: context.now, format: context.options.timerFormat)
192        let step = commitBuffer(context) { try $0.timerItem(value) }
193        guard started, case .commit(let result) = step else { return step }
194        return .commit(EditResult(baseRevision: result.baseRevision, edits: result.edits, selection: result.selection, effects: result.effects + InsertTimer.started(current, context)))
195    }
196}
197
198/// C-c C-x ;: `org-timer-set-timer`, a countdown for the entry's Effort, or for a time asked
199/// for.
200public struct TimerSetCountdown: OrgCommand {
201    public init() {}
202    public var id: String { "org.timer.set" }
203    public var title: String { "Set Countdown Timer…" }
204    public func applies(in context: EditContext) -> Bool { true }
205
206    public func run(in context: EditContext) -> CommandStep {
207        let current = timer(context)
208        if let current, !current.isCountdown { return .failed("Relative timer is running.  Stop first") }
209        let model = DocumentModel(tree: context.tree)
210        let heading = model.headings.lastIndex { $0.headingRange.lowerBound <= context.caret }
211        var minutes: String
212        if let heading, let effort = model.property("Effort", of: heading)?.value, effort.contains(where: { !$0.isWhitespace }),
213           let value = ColumnView.minutes(effort) {
214            minutes = String(Int(value.rounded(.down)))
215        } else {
216            let fallback = context.options.timerDefault
217            guard let answer = context.answers["minutes"] else {
218                return .prompt(Prompt(key: "minutes", message: "How much time left? (minutes or h:mm:ss) ", initial: fallback == "0" ? "" : fallback, requireMatch: false))
219            }
220            minutes = answer
221        }
222        if minutes.wholeMatch(of: /[0-9]+/) != nil { minutes += ":00" }
223        guard minutes.contains(where: \.isNumber) else { return TimerShowRemaining().run(in: context) }
224        if current != nil {
225            guard let replace = context.answers["replace"] else {
226                return .prompt(Prompt(key: "replace", message: "Replace current timer? (y or n) ", choices: ["y", "n"]))
227            }
228            if replace != "y" { return effects(context, [.message("No timer set")]) }
229        }
230        guard let fixed = OrgTimer.fixIncomplete(minutes) else { return .failed("Cannot parse HMS string \"\(minutes)\"") }
231        let seconds = OrgTimer.seconds(fixed)
232        // `org-get-heading`, which fails before the first heading.
233        let title: String? = heading == nil ? nil : EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings).orgGetHeading()
234        return effects(context, [.timer(OrgTimer(start: context.now.addingTimeInterval(Double(seconds)), isCountdown: true, title: title))])
235    }
236}
237
238/// `org-timer-show-remaining-time`.
239public struct TimerShowRemaining: OrgCommand {
240    public init() {}
241    public var id: String { "org.timer.show-remaining" }
242    public var title: String { "Show Remaining Countdown Time" }
243    public func applies(in context: EditContext) -> Bool { true }
244
245    public func run(in context: EditContext) -> CommandStep {
246        guard let current = timer(context), current.isCountdown else { return effects(context, [.message("No timer set")]) }
247        let left = Int(((current.paused ?? context.now).distance(to: current.start)).rounded(.down))
248        return effects(context, [.message("\(left / 60) minute(s) \(left % 60) seconds left before next time out")])
249    }
250}
251
252/// C-u C-u C-c C-x 0: `org-timer-change-times-in-region`, every h:mm:ss in the region moved by
253/// a difference asked for, by default the one that makes the first 0:00:00.
254public struct TimerChangeTimes: OrgCommand {
255    public init() {}
256    public var id: String { "org.timer.change-times" }
257    public var title: String { "Shift Timer Values in Region…" }
258    public func applies(in context: EditContext) -> Bool { context.selection.first.map { !$0.isEmpty } ?? false }
259
260    public func run(in context: EditContext) -> CommandStep {
261        guard let region = context.selection.first, !region.isEmpty else { return .failed("The mark is not set now, so there is no region") }
262        guard var delta = context.answers["delta"] else {
263            return .prompt(Prompt(key: "delta", message: "Enter time difference like \"-1:08:26\".  Default is first time to zero: ", requireMatch: false))
264        }
265        let pattern = try! NSRegularExpression(pattern: "[-+]?[0-9]+:[0-9]{2}:[0-9]{2}")
266        let first = pattern.firstMatch(in: context.text, range: NSRange(region))
267        if !delta.contains(where: { !$0.isWhitespace }), let first {
268            let stamp = (context.text as NSString).substring(with: first.range)
269            delta = stamp.hasPrefix("-") ? String(stamp.dropFirst()) : "-" + stamp
270        }
271        guard let fixed = OrgTimer.fixIncomplete(delta) else { return .failed("Cannot parse HMS string \"\(delta)\"") }
272        let seconds = OrgTimer.seconds(fixed)
273        guard seconds != 0 else { return .failed("No change") }
274        // `re-search-backward` from the region's end: the match starting nearest before the
275        // position and ending by it, so `0:00:00` inside `10:00:00` is found first.
276        let text = NSMutableString(string: context.text)
277        var position = region.upperBound
278        while position > region.lowerBound {
279            var found: NSRange?
280            var start = position - 1
281            while start >= region.lowerBound, found == nil {
282                found = pattern.firstMatch(in: text as String, options: .anchored, range: NSRange(location: start, length: position - start))?.range
283                start -= 1
284            }
285            guard let match = found else { break }
286            text.replaceCharacters(in: match, with: OrgTimer.hms(OrgTimer.seconds(text.substring(with: match)) + seconds))
287            position = match.location
288        }
289        let edits = TextEdit.between(context.text, text as String)
290        return .commit(EditResult(baseRevision: context.revision, edits: edits))
291    }
292}
293
294extension EmacsBuffer {
295    /// Whether the item at the caret starts with a timer, as `org-insert-item` checks.
296    static func atTimerList(_ context: EditContext) -> Bool {
297        let buffer = EmacsBuffer(context.text, point: context.caret, settings: context.tree.settings, options: context.options)
298        guard let item = buffer.inItem() else { return false }
299        buffer.point = item
300        return buffer.atTimerItem
301    }
302
303    /// `org-at-item-timer-p`.
304    var atTimerItem: Bool {
305        saveExcursion {
306            beginningOfLine()
307            guard let match = looking(itemPattern) else { return false }
308            point = match[0]!.upperBound
309            // `org-list-at-regexp-after-bullet-p`: past a counter, not a checkbox.
310            let counter = options.listAllowAlphabetical ? "(?:\\[@(?:start:)?([0-9]+|[A-Za-z])\\][ \\t]*)?" : "(?:\\[@(?:start:)?[0-9]+\\][ \\t]*)?"
311            return looking(counter + "([0-9]+:[0-9]+:[0-9]+)[ \\t]+::[ \\t]+") != nil
312        }
313    }
314
315    /// `org-timer-item` with the timer's `value`.
316    func timerItem(_ value: String) throws {
317        let pos = point
318        if let item = inItem() {
319            point = item
320            guard atTimerItem else {
321                point = pos
322                throw UserError(message: "This is not a timer list")
323            }
324            var structure = listStruct()
325            structure = insertItem(at: pos, structure, structure.prevs, checkbox: false, afterBullet: value + ":: ", splitLine: options.metaReturnMaySplitLine)
326            writeStruct(&structure, structure.parents)
327            beginningOfLine()
328            if let match = looking(Self.fullItemPattern) { point = match[0]!.upperBound }
329            return
330        }
331        // `org-indent-line` outside a list, with `org-adapt-indentation` nil: as the line
332        // above that isn't blank, or at column 0 after a heading or at the start.
333        let column = saveExcursion { () -> Int in
334            beginningOfLine()
335            skipBackward([32, 9, 10, 13])
336            guard point > 0 else { return 0 }
337            beginningOfLine()
338            return atHeading ? 0 : currentTextIndentation
339        }
340        indentLineTo(column)
341        insert("- " + value + ":: ")
342    }
343}