Sources/OrgCore/Commands/ClockHistory.swift

196 lines · 9971 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. Without
 94    /// `ClockTask.titleKey`, hidden entries hashed with it are kept unchanged.
 95    public static func push(_ task: ClockTask, onto history: [ClockTask], length: Int, text: (String) -> String?) -> [ClockTask] {
 96        let length = max(1, length)
 97        var texts: [String: String?] = [:]
 98        func read(_ path: String) -> String? {
 99            if let cached = texts[path] { return cached }
100            let value = text(path)
101            texts[path] = value
102            return value
103        }
104        let target = read(task.path).flatMap { task.locate(in: $0) }
105        var kept: [ClockTask] = []
106        for entry in history {
107            // A hidden task hashed with the kept key can't be found with this run's; it stays as it was.
108            if ClockTask.titleKey == nil, entry.titleHash.map({ !$0.hasPrefix("s:") }) == true {
109                kept.append(entry)
110                continue
111            }
112            guard let contents = read(entry.path), let current = entry.refreshed(in: contents) else { continue }
113            if entry.path == task.path, let target, current.locate(in: contents) == target { continue }
114            kept.append(current)
115        }
116        if kept.count >= length { kept = Array(kept.prefix(length - 1)) }
117        return [task] + kept
118    }
119
120    /// One line of the selection: its key, the section it is under and `[k] category  task`.
121    public struct Choice: Equatable, Sendable {
122        public let key: Character
123        public let section: String
124        public let task: ClockTask
125        /// `%-12s  %s` of the category and the heading without tags.
126        public let line: String
127    }
128
129    /// `org-clock-select-task`'s entries: the default task (`d`), the interrupted one (`i`),
130    /// the clocking one (`c`), then recent tasks `1`–`9`, `A`… Nil when there is no recent
131    /// clock. Entries that are gone are left out.
132    public static func selection(
133        defaultTask: ClockTask?, interrupted: ClockTask?, current: ClockTask?, history: [ClockTask], text: (String) -> String?
134    ) -> [Choice]? {
135        // Successive duplicates go.
136        var recent: [ClockTask] = []
137        for task in history where task != recent.last { recent.append(task) }
138        guard !recent.isEmpty else { return nil }
139        var choices: [Choice] = []
140        func add(_ key: Character, _ section: String, _ task: ClockTask?) -> Bool {
141            guard let task, let contents = text(task.path), let line = line(task, in: contents) else { return false }
142            choices.append(Choice(key: key, section: section, task: task, line: line))
143            return true
144        }
145        _ = add("d", "Default Task", defaultTask)
146        _ = add("i", "The task interrupted by starting the last one", interrupted)
147        _ = add("c", "Current Clocking Task", current)
148        var i = 0
149        for task in recent {
150            guard let contents = text(task.path), line(task, in: contents) != nil else { continue }
151            i += 1
152            let scalar = i < 10 ? 48 + i : 65 + i - 10
153            _ = add(Character(UnicodeScalar(UInt8(clamping: scalar))), "Recent Tasks", task)
154        }
155        return choices
156    }
157
158    /// The prompt's keys and lines, under their section titles.
159    public static func fastSelection(_ choices: [Choice]) -> FastSelection {
160        var items: [FastSelection.Item] = []
161        var section: String?
162        for choice in choices {
163            if choice.section != section {
164                section = choice.section
165                items.append(.label(choice.section))
166            }
167            items.append(.option(key: choice.key, name: choice.line))
168            items.append(.newline)
169        }
170        return FastSelection(items: items, multiple: false)
171    }
172
173    /// `org-clock-insert-selection-line`'s text for a task, nil when it is gone.
174    public static func line(_ task: ClockTask, in text: String) -> String? {
175        let model = DocumentModel(tree: OrgParser.parse(text))
176        guard let index = task.index(in: model) else { return nil }
177        let heading = model.headings[index]
178        let category = category(of: index, in: model, text: text, path: task.path)
179        let words = [heading.todo, heading.priority.map { "[#\($0)]" }, heading.title].compactMap { $0 }.filter { !$0.isEmpty }
180        let padded = category.count >= 12 ? category : category + String(repeating: " ", count: 12 - category.count)
181        return padded + "  " + words.joined(separator: " ")
182    }
183
184    /// `org-get-category`: the entry's or an ancestor's CATEGORY, `#+CATEGORY`, or the file
185    /// name without its extension.
186    static func category(of index: Int, in model: DocumentModel, text: String, path: String) -> String {
187        for layer in [index] + model.ancestors(of: index).reversed() {
188            if let value = model.headings[layer].properties.last(where: { $0.key.uppercased() == "CATEGORY" && !$0.additive })?.value {
189                return value
190            }
191        }
192        let keyword = text.components(separatedBy: "\n").last { $0.uppercased().hasPrefix("#+CATEGORY:") }
193            .map { String($0.dropFirst("#+CATEGORY:".count)).trimmingCharacters(in: .whitespaces) }
194        return keyword ?? model.property("CATEGORY", of: nil)?.value ?? ((path as NSString).lastPathComponent as NSString).deletingPathExtension
195    }
196}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form