Sources/OrgCore/Commands/Clock.swift
298 lines · 13704 bytes
21 symbols in this file
1import Foundation
2
3// Clocking (org-clock.el, Org 9.8.7) with `org-clock-into-drawer` and the CLOCK_INTO_DRAWER
4// property, `org-clock-rounding-minutes`, `org-clock-out-remove-zero-time-clocks`,
5// `org-clock-in-switch-to-state`, `org-log-states-order-reversed` t (newest first) and no
6// resume.
7
8extension EmacsBuffer {
9 /// What `org-clock-into-drawer` comes to for an entry.
10 enum ClockDrawer: Equatable {
11 case none
12 /// Into the drawer once there are this many clock lines.
13 case count(Int)
14 case named(String)
15 }
16
17 /// `org-log-into-drawer` for the entry: the setting, `#+STARTUP: logdrawer` and the
18 /// LOG_INTO_DRAWER property.
19 func logIntoDrawer() -> String? { logSettings().drawer }
20
21 /// `org-clock-into-drawer` (the function): the entry's CLOCK_INTO_DRAWER over the setting.
22 func clockIntoDrawer() -> ClockDrawer {
23 func read(_ value: String) -> ClockDrawer? {
24 switch value.trimmingCharacters(in: .whitespaces) {
25 case "nil": return ClockDrawer.none
26 case "t": return .named(logIntoDrawer() ?? "LOGBOOK")
27 case "": return nil
28 case let text where text.allSatisfy(\.isASCII) && text.allSatisfy(\.isNumber): return .count(Int(text) ?? 0)
29 case let name: return .named(name)
30 }
31 }
32 if let property = inheritedProperty("CLOCK_INTO_DRAWER")?.value, let value = read(property) { return value }
33 return options.clockIntoDrawer.flatMap(read) ?? .named(logIntoDrawer() ?? "LOGBOOK")
34 }
35
36 /// `org-clock-drawer-name`.
37 func clockDrawerName() -> String? {
38 switch clockIntoDrawer() {
39 case .none: nil
40 case .count: logIntoDrawer() ?? "LOGBOOK"
41 case .named(let name): name
42 }
43 }
44
45 static let openClockPattern = "^[ \\t]*CLOCK: \\[([0-9]{4}-[0-9]{2}-[0-9]{2} *[^\\]\\s]+ +[012][0-9]:[0-5][0-9])\\][ \\t]*$"
46
47 /// `org-clock-find-position` without `find-unclosed`.
48 func clockFindPosition() throws {
49 let beg = try backToHeading()
50 let end = saveExcursion { () -> Int in
51 _ = outlineNextHeading()
52 return point
53 }
54 let into = clockIntoDrawer()
55 let drawer = clockDrawerName()
56 if let drawer {
57 let drawerPattern = "^[ \\t]*:" + NSRegularExpression.escapedPattern(for: drawer) + ":[ \\t]*$"
58 point = beg
59 while let match = searchForward(drawerPattern, bound: end, caseInsensitive: false) {
60 if element(at: lineStart(match[0]!.lowerBound))?.kind == .drawer {
61 point = match[0]!.upperBound
62 forwardLine(1)
63 return
64 }
65 }
66 }
67 point = beg
68 var positions: [Int] = []
69 saveExcursion {
70 while let match = searchForward("^[ \\t]*CLOCK:", bound: end, caseInsensitive: false) {
71 if element(at: lineStart(match[0]!.lowerBound))?.kind == .clock { positions.insert(lineStart(match[0]!.lowerBound), at: 0) }
72 }
73 }
74 if positions.isEmpty {
75 endOfMetaData()
76 if !bolp { insertBeforeMarkers("\n") }
77 let creates: Bool = switch into {
78 case .none: false
79 case .count(let n): n < 2
80 case .named: true
81 }
82 if creates, let drawer {
83 insertBeforeMarkers(":" + drawer + ":\n:END:\n")
84 forwardLine(-1)
85 }
86 return
87 }
88 // Without a drawer, or with fewer clocks than the setting's number, the new clock goes
89 // first.
90 let wraps: Bool = switch into {
91 case .count(let n): positions.count + 1 >= n
92 default: drawer != nil
93 }
94 guard wraps, let drawer else {
95 point = positions.last!
96 return
97 }
98 // Clocks outside a drawer move into a new one.
99 endOfMetaData()
100 let start = point
101 var moved: [String] = []
102 for position in positions {
103 let lineStartOffset = position
104 let next = min(length, lineEnd(lineStartOffset) + 1)
105 var from = lineStartOffset
106 while from > 0, let c = character(at: from - 1), c == 32 || c == 9 || c == 10 || c == 13 { from -= 1 }
107 from = min(length, lineEnd(from) + 1)
108 if from > lineStartOffset { from = lineStartOffset }
109 let text = substring(from, next).trimmingCharacters(in: .whitespacesAndNewlines)
110 deleteRegion(from, next)
111 moved.append(text)
112 }
113 point = min(start, length)
114 insert(moved.joined(separator: "\n") + "\n:END:\n")
115 let endMarker = marker(point)
116 defer { release(endMarker) }
117 point = start
118 saveExcursion { insertBeforeMarkers(":" + drawer + ":\n") }
119 forwardLine(1)
120 }
121
122 /// `org-current-time` with `org-clock-rounding-minutes`: the minute rounded to a multiple,
123 /// with `past` one not after now.
124 func clockTime(past: Bool) -> Date {
125 let r = options.clockRoundingMinutes
126 guard r >= 1 else { return now }
127 var c = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: now)
128 c.minute = r * Int((Double(c.minute!) / Double(r)).rounded(.toNearestOrEven))
129 c.second = 0
130 guard let rounded = calendar.date(from: c) else { return now }
131 return !past || rounded < now ? rounded : rounded.addingTimeInterval(-Double(r * 60))
132 }
133
134 /// `org-clock-in-switch-to-state` on the heading at point, unless it has that keyword.
135 func switchToClockInState(answers: [String: String]) throws {
136 guard let state = options.clockInSwitchToState, !state.isEmpty else { return }
137 try saveExcursion {
138 try backToHeading()
139 let previous = todoKeyword
140 guard previous != state else { return }
141 guard keywordsInOrder.contains(state) else { throw UserError(message: "State `\(state)' not valid in this file") }
142 // `org-todo` stops at a blocker, and clocking in goes on.
143 guard (try? checkTodoBlocking(from: previous, to: state)) != nil else { return }
144 setTodoKeyword(state)
145 var answers = answers
146 if answers["note"] == nil { answers["note"] = "" }
147 try afterTodoChange(previous: previous, answers: answers)
148 }
149 }
150
151 /// `org-clock-in` on the heading at point. Returns the clock's start stamp.
152 @discardableResult
153 func clockIn(answers: [String: String] = [:]) throws -> String {
154 let start = point
155 let pointMarker = marker(start)
156 defer {
157 point = pointMarker.position
158 release(pointMarker)
159 }
160 if eobp, !atHeadingLine { point = lineStart(max(0, lineStart(point) - 1)) }
161 try switchToClockInState(answers: answers)
162 try clockFindPosition()
163 insertBeforeMarkers("\n")
164 point -= 1
165 if point > 0, saveExcursion({ () -> Int? in
166 point = lineStart(point) - 1
167 return point >= 0 ? inItem() : nil
168 }) != nil {
169 beginningOfLine()
170 let current = substring(point, lineEnd(point)).prefix { $0 == " " || $0 == "\t" }.count
171 indentLineTo(max(0, current - 2))
172 }
173 insert("CLOCK: ")
174 let components = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: clockTime(past: true))
175 let stamp = insertTimestamp(components, withTime: true, inactive: true)
176 // `org-indent-line` puts lines in a drawer at column 0 without adapted indentation.
177 let lineText = substring(lineStart(point), lineEnd(point))
178 let indent = lineText.prefix { $0 == " " || $0 == "\t" }.count
179 if indent > 0 { deleteRegion(lineStart(point), lineStart(point) + indent) }
180 return String(stamp.dropFirst().dropLast())
181 }
182
183 var atHeadingLine: Bool { lookingAtLine("^\\*+ ") }
184
185 /// The running clock's line: `CLOCK: [start]` with nothing after it.
186 func runningClockLine(_ start: String) -> Int? {
187 let pattern = "^[ \\t]*CLOCK: \\[" + NSRegularExpression.escapedPattern(for: start) + "\\][ \\t]*$"
188 return saveExcursion {
189 point = 0
190 return searchForward(pattern, caseInsensitive: false).map { lineStart($0[0]!.lowerBound) }
191 }
192 }
193
194 /// `org-clock-out` for the clock that started at `start`.
195 func clockOut(_ start: String) throws {
196 guard let line = runningClockLine(start) else { throw UserError(message: "Clock start time is gone") }
197 point = line
198 guard let match = looking("[ \\t]*CLOCK: \\[([^\\]]+)\\]", caseInsensitive: false) else { throw UserError(message: "Clock start time is gone") }
199 point = match[0]!.upperBound
200 deleteRegion(point, lineEnd(point))
201 insert("--")
202 let components = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: clockTime(past: false))
203 let end = insertTimestamp(components, withTime: true, inactive: true)
204 guard let startTime = Self.parseTimeString(start), let endTime = Self.parseTimeString(String(end.dropFirst().dropLast())),
205 let a = calendar.date(from: startTime), let b = calendar.date(from: endTime) else { throw UserError(message: "Clock start time is gone") }
206 let seconds = Int(b.timeIntervalSince(a))
207 let hours = Int((Double(seconds) / 3600).rounded(.down))
208 let minutes = Int((Double(seconds - hours * 3600) / 60).rounded(.down))
209 insert(" => " + String(format: "%2d:%02d", hours, minutes))
210 if options.clockOutRemoveZeroTimeClocks, hours == 0, minutes == 0 {
211 deleteRegion(lineStart(point), min(length, lineEnd(point) + 1))
212 }
213 removeEmptyClockDrawer()
214 }
215
216 /// `org-clock-cancel`: the running clock's line goes, and the drawer if it empties.
217 func clockCancel(_ start: String) throws {
218 guard let line = runningClockLine(start) else { throw UserError(message: "No active clock") }
219 point = lineEnd(line)
220 let from = max(0, line - 1)
221 deleteRegion(from, lineEnd(line))
222 point = from
223 removeEmptyDrawer(at: point)
224 }
225
226 /// `org-clock-remove-empty-clock-drawer` for the subtree at point.
227 func removeEmptyClockDrawer() {
228 saveExcursion {
229 guard let heading = try? backToHeading(), let drawer = clockDrawerName() else { return }
230 let end = saveExcursion { () -> Int in
231 point = heading
232 return endOfSubtree()
233 }
234 point = heading
235 let pattern = "(?i)^[ \\t]*:" + NSRegularExpression.escapedPattern(for: drawer) + ":[ \\t]*$"
236 while let match = searchForward(pattern, bound: end, caseInsensitive: true) {
237 removeEmptyDrawer(at: match[0]!.upperBound)
238 }
239 }
240 }
241
242 /// `org-remove-empty-drawer-at`.
243 func removeEmptyDrawer(at position: Int) {
244 let lineStartOffset = lineStart(min(position, length))
245 let line = substring(lineStartOffset, lineEnd(lineStartOffset))
246 guard line.trimmingCharacters(in: .whitespaces).range(of: "^:[\\w-]+:$", options: .regularExpression) != nil,
247 line.trimmingCharacters(in: .whitespaces).uppercased() != ":END:" else { return }
248 let next = min(length, lineEnd(lineStartOffset) + 1)
249 let following = substring(next, lineEnd(next))
250 guard following.trimmingCharacters(in: .whitespaces).uppercased() == ":END:" else { return }
251 deleteRegion(lineStartOffset, min(length, lineEnd(next) + 1))
252 }
253}
254
255/// C-c C-x C-i: `org-clock-in` at the heading at the caret.
256public struct ClockIn: OrgCommand {
257 public init() {}
258 public var id: String { "org.clock.in" }
259 public var title: String { "Clock In" }
260 public func applies(in context: EditContext) -> Bool { entryHeading(at: context.caret, in: context.tree) != nil }
261 public func run(in context: EditContext) -> CommandStep {
262 guard entryHeading(at: context.caret, in: context.tree) != nil else { return .failed("Before first headline") }
263 return commitBuffer(context) { try $0.clockIn(answers: context.answers) }
264 }
265
266 /// The start of the clock `ClockIn` left running in the entry at `offset`.
267 public static func runningStart(in text: String, near offset: Int) -> String? {
268 let buffer = EmacsBuffer(text, point: offset)
269 guard let heading = try? buffer.backToHeading() else { return nil }
270 let end = buffer.saveExcursion { () -> Int in
271 _ = buffer.outlineNextHeading()
272 return buffer.point
273 }
274 buffer.point = heading
275 guard let match = buffer.searchForward(EmacsBuffer.openClockPattern, bound: end, caseInsensitive: false) else { return nil }
276 return buffer.substring(match[1]!.lowerBound, match[1]!.upperBound)
277 }
278}
279
280/// C-c C-x C-o and C-c C-x C-q for the clock that started at `start`.
281public struct ClockOut: OrgCommand {
282 public let start: String
283 public let cancel: Bool
284 public init(start: String, cancel: Bool = false) {
285 self.start = start
286 self.cancel = cancel
287 }
288 public var id: String { cancel ? "org.clock.cancel" : "org.clock.out" }
289 public var title: String { cancel ? "Cancel Clock" : "Clock Out" }
290 public func applies(in context: EditContext) -> Bool { true }
291 public func run(in context: EditContext) -> CommandStep {
292 commitBuffer(context) { buffer in
293 try buffer.saveExcursion {
294 if cancel { try buffer.clockCancel(start) } else { try buffer.clockOut(start) }
295 }
296 }
297 }
298}