Sources/OrgCore/Commands/ClockHistory.swift
190 lines · 9606 bytes
1import CryptoKit
2import Foundation
3
4// Clock history and task selection (`org-clock-history`, `org-clock-history-push`,
5// `org-clock-select-task`, Org 9.8.7). Org keeps markers, which follow edits; a task here is
6// found again by its ID, else by its heading's position among the file's headings and its
7// title, else by its title.
8
9/// A clocked entry, as `org-clock-history` and `org-clock-default-task` remember it.
10public struct ClockTask: Codable, Equatable, Hashable, Sendable {
11 public let path: String
12 public let title: String
13 /// The heading's index among the file's headings.
14 public let ordinal: Int
15 public let id: String?
16 /// For a task whose title is a placeholder for one that isn't kept (an encrypted
17 /// heading's): an HMAC of the real title, which finds it with its ID or position.
18 public let titleHash: String?
19
20 /// The key titles are hashed with, kept by the app; without one, a key of this run's
21 /// only, and such tasks (`isSessionOnly`) aren't kept past it.
22 nonisolated(unsafe) public static var titleKey: SymmetricKey?
23 static let sessionKey = SymmetricKey(size: .bits256)
24
25 /// `title`'s HMAC-SHA256, hex, prefixed `s:` when made with this run's key.
26 public static func titleDigest(_ title: String) -> String {
27 func hex(_ key: SymmetricKey) -> String {
28 HMAC<SHA256>.authenticationCode(for: Data(title.utf8), using: key).map { String(format: "%02x", $0) }.joined()
29 }
30 if let titleKey { return hex(titleKey) }
31 return "s:" + hex(sessionKey)
32 }
33
34 /// Whether the task can be found only in this run: hidden, without an ID, hashed with this
35 /// run's key.
36 public var isSessionOnly: Bool { id == nil && titleHash?.hasPrefix("s:") == true }
37
38 public init(path: String, title: String, ordinal: Int, id: String?, titleHash: String? = nil) {
39 self.path = path
40 self.title = title
41 self.ordinal = ordinal
42 self.id = id
43 self.titleHash = titleHash
44 }
45
46 /// The entry containing `offset`; nil before the first heading.
47 public static func at(_ offset: Int, in text: String, path: String) -> ClockTask? {
48 let model = DocumentModel(tree: OrgParser.parse(text))
49 guard let index = model.headings.lastIndex(where: { $0.headingRange.lowerBound <= offset }) else { return nil }
50 let heading = model.headings[index]
51 return ClockTask(path: path, title: heading.title, ordinal: index, id: heading.id)
52 }
53
54 /// The heading's index in `model`, or nil when the entry is gone: by ID, then by position
55 /// and title, or by title; a task kept without its title by position alone.
56 public func index(in model: DocumentModel) -> Int? {
57 if let id, let index = model.headings.firstIndex(where: { $0.id == id }) { return index }
58 if let titleHash {
59 func matches(_ index: Int) -> Bool { Self.titleDigest(model.headings[index].title) == titleHash }
60 if ordinal < model.headings.count, matches(ordinal) { return ordinal }
61 return model.headings.indices.first(where: matches)
62 }
63 if ordinal < model.headings.count, model.headings[ordinal].title == title { return ordinal }
64 return model.headings.firstIndex { $0.title == title }
65 }
66
67 /// Where the heading starts in `text`, or nil when the entry is gone.
68 public func locate(in text: String) -> Int? {
69 let model = DocumentModel(tree: OrgParser.parse(text))
70 return index(in: model).map { model.headings[$0].headingRange.lowerBound }
71 }
72
73 /// The task as found in `text`, with its current position; nil when the entry is gone.
74 public func refreshed(in text: String) -> ClockTask? {
75 let model = DocumentModel(tree: OrgParser.parse(text))
76 guard let index = index(in: model) else { return nil }
77 return ClockTask(path: path, title: model.headings[index].title, ordinal: index, id: model.headings[index].id)
78 .hiding(titleHash == nil ? nil : title)
79 }
80
81 /// The task with `placeholder` for its title, or as it is with nil.
82 public func hiding(_ placeholder: String?) -> ClockTask {
83 guard let placeholder else { return self }
84 return ClockTask(path: path, title: placeholder, ordinal: ordinal, id: id, titleHash: titleHash ?? Self.titleDigest(title))
85 }
86}
87
88public enum ClockHistory {
89 /// `org-clock-history-length`.
90 public static let defaultLength = 5
91
92 /// `org-clock-history-push`: `task` goes first, other entries for the same heading and
93 /// entries that are gone leave, and the oldest go past `length`. `text` reads a file.
94 public static func push(_ task: ClockTask, onto history: [ClockTask], length: Int, text: (String) -> String?) -> [ClockTask] {
95 let length = max(1, length)
96 var texts: [String: String?] = [:]
97 func read(_ path: String) -> String? {
98 if let cached = texts[path] { return cached }
99 let value = text(path)
100 texts[path] = value
101 return value
102 }
103 let target = read(task.path).flatMap { task.locate(in: $0) }
104 var kept: [ClockTask] = []
105 for entry in history {
106 guard let contents = read(entry.path), let current = entry.refreshed(in: contents) else { continue }
107 if entry.path == task.path, let target, current.locate(in: contents) == target { continue }
108 kept.append(current)
109 }
110 if kept.count >= length { kept = Array(kept.prefix(length - 1)) }
111 return [task] + kept
112 }
113
114 /// One line of the selection: its key, the section it is under and `[k] category task`.
115 public struct Choice: Equatable, Sendable {
116 public let key: Character
117 public let section: String
118 public let task: ClockTask
119 /// `%-12s %s` of the category and the heading without tags.
120 public let line: String
121 }
122
123 /// `org-clock-select-task`'s entries: the default task (`d`), the interrupted one (`i`),
124 /// the clocking one (`c`), then recent tasks `1`–`9`, `A`… Nil when there is no recent
125 /// clock. Entries that are gone are left out.
126 public static func selection(
127 defaultTask: ClockTask?, interrupted: ClockTask?, current: ClockTask?, history: [ClockTask], text: (String) -> String?
128 ) -> [Choice]? {
129 // Successive duplicates go.
130 var recent: [ClockTask] = []
131 for task in history where task != recent.last { recent.append(task) }
132 guard !recent.isEmpty else { return nil }
133 var choices: [Choice] = []
134 func add(_ key: Character, _ section: String, _ task: ClockTask?) -> Bool {
135 guard let task, let contents = text(task.path), let line = line(task, in: contents) else { return false }
136 choices.append(Choice(key: key, section: section, task: task, line: line))
137 return true
138 }
139 _ = add("d", "Default Task", defaultTask)
140 _ = add("i", "The task interrupted by starting the last one", interrupted)
141 _ = add("c", "Current Clocking Task", current)
142 var i = 0
143 for task in recent {
144 guard let contents = text(task.path), line(task, in: contents) != nil else { continue }
145 i += 1
146 let scalar = i < 10 ? 48 + i : 65 + i - 10
147 _ = add(Character(UnicodeScalar(UInt8(clamping: scalar))), "Recent Tasks", task)
148 }
149 return choices
150 }
151
152 /// The prompt's keys and lines, under their section titles.
153 public static func fastSelection(_ choices: [Choice]) -> FastSelection {
154 var items: [FastSelection.Item] = []
155 var section: String?
156 for choice in choices {
157 if choice.section != section {
158 section = choice.section
159 items.append(.label(choice.section))
160 }
161 items.append(.option(key: choice.key, name: choice.line))
162 items.append(.newline)
163 }
164 return FastSelection(items: items, multiple: false)
165 }
166
167 /// `org-clock-insert-selection-line`'s text for a task, nil when it is gone.
168 public static func line(_ task: ClockTask, in text: String) -> String? {
169 let model = DocumentModel(tree: OrgParser.parse(text))
170 guard let index = task.index(in: model) else { return nil }
171 let heading = model.headings[index]
172 let category = category(of: index, in: model, text: text, path: task.path)
173 let words = [heading.todo, heading.priority.map { "[#\($0)]" }, heading.title].compactMap { $0 }.filter { !$0.isEmpty }
174 let padded = category.count >= 12 ? category : category + String(repeating: " ", count: 12 - category.count)
175 return padded + " " + words.joined(separator: " ")
176 }
177
178 /// `org-get-category`: the entry's or an ancestor's CATEGORY, `#+CATEGORY`, or the file
179 /// name without its extension.
180 static func category(of index: Int, in model: DocumentModel, text: String, path: String) -> String {
181 for layer in [index] + model.ancestors(of: index).reversed() {
182 if let value = model.headings[layer].properties.last(where: { $0.key.uppercased() == "CATEGORY" && !$0.additive })?.value {
183 return value
184 }
185 }
186 let keyword = text.components(separatedBy: "\n").last { $0.uppercased().hasPrefix("#+CATEGORY:") }
187 .map { String($0.dropFirst("#+CATEGORY:".count)).trimmingCharacters(in: .whitespaces) }
188 return keyword ?? model.property("CATEGORY", of: nil)?.value ?? ((path as NSString).lastPathComponent as NSString).deletingPathExtension
189 }
190}