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