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