Sources/OrgCore/Agenda/PrefixFormat.swift

f08ff8962219d175d80f8b87332bdec6ca0ec21e
orgstar/Sources/OrgCore/Agenda/PrefixFormat.swift history · blame · raw

82 lines · 3915 bytes

 1import Foundation
 2
 3/// `org-agenda-prefix-format` for one view, compiled as `org-compile-prefix-format` does:
 4/// `%c` category, `%t` time, `%l` level, `%s` extra, `%e` effort, `%b` breadcrumbs, `%i` icon
 5/// (none in Orgstar), each with an optional `?` (empty when the value is), a `%-12`-style
 6/// width with an optional `.N` limit on categories, and a punctuation character added after a
 7/// non-empty value. `%(…)` forms run Lisp; they are empty here.
 8public struct PrefixFormat: Sendable, Equatable {
 9    enum Piece: Sendable, Equatable {
10        case literal(String)
11        case field(key: Character, optional: Bool, width: String, punctuation: String)
12    }
13
14    let pieces: [Piece]
15    /// `org-prefix-has-time`: times move out of the heading into the prefix.
16    let hasTime: Bool
17    /// `.N` in the category width: categories this long or longer are cut to N - 1.
18    let categoryMaxLength: Int?
19
20    public init(_ format: String) {
21        let regex = try! NSRegularExpression(pattern: "%(\\?)?([-+]?[0-9.]*)([ .;,:!?=|/<>]?)([cltseib]|\\(.+?\\))")
22        let ns = format as NSString
23        var pieces: [Piece] = []
24        var hasTime = false
25        var maxLength: Int?
26        var at = 0
27        for m in regex.matches(in: format, range: NSRange(location: 0, length: ns.length)) {
28            if m.range.location > at { pieces.append(.literal(ns.substring(with: NSRange(location: at, length: m.range.location - at)))) }
29            let key = ns.substring(with: m.range(at: 4))
30            let width = ns.substring(with: m.range(at: 2))
31            if key.hasPrefix("(") {
32                pieces.append(.field(key: "(", optional: false, width: width, punctuation: ""))
33            } else {
34                let k = key.first!
35                if k == "t" { hasTime = true }
36                if k == "c", let dot = width.firstIndex(of: ".") { maxLength = Int(width[width.index(after: dot)...].prefix { $0.isNumber }) }
37                pieces.append(.field(key: k, optional: m.range(at: 1).location != NSNotFound, width: width, punctuation: ns.substring(with: m.range(at: 3))))
38            }
39            at = NSMaxRange(m.range)
40        }
41        if at < ns.length { pieces.append(.literal(ns.substring(from: at))) }
42        self.pieces = pieces
43        self.hasTime = hasTime
44        self.categoryMaxLength = maxLength
45    }
46
47    /// The prefix for these values, by field key.
48    func render(_ values: [Character: String]) -> String {
49        var out = ""
50        for piece in pieces {
51            switch piece {
52            case .literal(let s): out += s
53            case .field(let key, let optional, let width, let punctuation):
54                var value = values[key] ?? ""
55                if key == "c", let max = categoryMaxLength, value.count >= max { value = String(value.prefix(max - 1)) }
56                if value.isEmpty {
57                    out += optional ? "" : Self.format("", width)
58                } else {
59                    out += Self.format(value + punctuation, width)
60                }
61            }
62        }
63        return out
64    }
65
66    /// Emacs `format` with `%WIDTHs` or `%-WIDTH.PRECISIONs`.
67    static func format(_ s: String, _ spec: String) -> String {
68        var spec = Substring(spec)
69        let left = spec.first == "-"
70        if left || spec.first == "+" { spec = spec.dropFirst() }
71        let parts = spec.split(separator: ".", omittingEmptySubsequences: false)
72        let width = Int(parts.first ?? "") ?? 0
73        var value = s
74        if parts.count > 1, let precision = Int(parts[1]) { value = String(value.prefix(precision)) }
75        let padding = String(repeating: " ", count: max(0, width - displayWidth(value)))
76        return left ? value + padding : padding + value
77    }
78
79    public static let defaults: [String: String] = [
80        "agenda": " %i %-12:c%?-12t% s", "todo": " %i %-12:c", "tags": " %i %-12:c", "search": " %i %-12:c",
81    ]
82}