Sources/OrgCore/Commands/ClockHistory.swift

fbc792eb21866a31f8edcffd23f5105df3be2348
orgstar/Sources/OrgCore/Commands/ClockHistory.swift

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