Sources/OrgCore/Commands/ColumnView.swift

524b5afe95ec3f3e3d1daba761a9e181f09cf88a
orgstar/Sources/OrgCore/Commands/ColumnView.swift history · blame · raw

422 lines · 21561 bytes

  1import Foundation
  2
  3// Column view (`org-colview.el`, Org 9.8.7): the column format, values and summaries of each
  4// entry, and the `columnview` dynamic block that captures them.
  5
  6public enum ColumnView {
  7    /// One column of `org-columns-compile-format`.
  8    public struct Spec: Sendable, Equatable {
  9        public let property: String
 10        public let title: String
 11        public let width: Int?
 12        public let summary: String?
 13        public let format: String?
 14    }
 15
 16    public struct Row: Sendable, Equatable {
 17        public let level: Int
 18        /// Start of the heading line.
 19        public let start: Int
 20        public let values: [String]
 21    }
 22
 23    public struct View: Sendable, Equatable {
 24        public let specs: [Spec]
 25        public let rows: [Row]
 26    }
 27
 28    public static let defaultFormat = "%25ITEM %TODO %3PRIORITY %TAGS"
 29
 30    /// `org-columns-compile-format`.
 31    public static func compile(_ format: String) -> [Spec] {
 32        format.matches(of: /%([0-9]+)?([A-Za-z0-9_-]+)(?:\(([^)]*)\))?(?:\{([^}]*)\})?\s*/).map { m in
 33            let property = String(m.2)
 34            let title = m.3.map(String.init).flatMap { $0.contains(where: { !$0.isWhitespace }) ? $0 : nil } ?? property
 35            var summary = m.4.map(String.init).flatMap { $0.contains(where: { !$0.isWhitespace }) ? $0 : nil }
 36            var fmt: String?
 37            if let s = summary, let semicolon = s.firstIndex(of: ";") {
 38                fmt = String(s[s.index(after: semicolon)...])
 39                summary = String(s[..<semicolon])
 40            }
 41            return Spec(property: property.uppercased(), title: title, width: m.1.flatMap { Int($0) }, summary: summary, format: fmt)
 42        }
 43    }
 44
 45    // MARK: - Numbers and durations as Emacs Lisp has them
 46
 47    /// A number from `string-to-number`: an integer unless the text has a fraction or exponent.
 48    enum Number {
 49        case int(Int)
 50        case float(Double)
 51
 52        init(_ s: String) {
 53            let t = s.trimmingCharacters(in: .whitespaces)
 54            if let m = t.prefixMatch(of: /[-+]?[0-9]+(?![.eE0-9])/), let i = Int(m.0) { self = .int(i); return }
 55            if let m = t.prefixMatch(of: /[-+]?(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][-+]?[0-9]+)?/), let d = Double(m.0) {
 56                self = m.0.contains(where: { $0 == "." || $0 == "e" || $0 == "E" }) ? .float(d) : .int(Int(d)); return
 57            }
 58            self = .int(0)
 59        }
 60
 61        var double: Double {
 62            switch self {
 63            case .int(let i): Double(i)
 64            case .float(let d): d
 65            }
 66        }
 67
 68        /// `format "%s"`.
 69        var lisp: String {
 70            switch self {
 71            case .int(let i): String(i)
 72            case .float(let d): d.isFinite && d == d.rounded() && abs(d) < 1e16 ? String(format: "%.1f", d) : "\(d)"
 73            }
 74        }
 75
 76        static func + (a: Number, b: Number) -> Number {
 77            if case .int(let x) = a, case .int(let y) = b { return .int(x + y) }
 78            return .float(a.double + b.double)
 79        }
 80    }
 81
 82    /// `format FMT` with a number, for the formats summaries use.
 83    static func format(_ fmt: String?, _ n: Number) -> String {
 84        guard let fmt else { return n.lisp }
 85        if fmt.contains("%d") { return String(format: fmt.replacingOccurrences(of: "%d", with: "%ld"), Int(n.double)) }
 86        if fmt.contains("%s") { return fmt.replacingOccurrences(of: "%s", with: n.lisp) }
 87        return String(format: fmt, n.double)
 88    }
 89
 90    static let unitMinutes: [(String, Double)] = [("min", 1), ("h", 60), ("d", 1440), ("w", 10080), ("m", 43200), ("y", 525960)]
 91
 92    /// `org-duration-to-minutes`.
 93    public static func minutes(_ duration: String) -> Double? {
 94        let s = duration.trimmingCharacters(in: .whitespaces)
 95        if s.isEmpty { return 0 }
 96        if s.wholeMatch(of: /[0-9]+(?::[0-9]{2}){1,2}/) != nil {
 97            let parts = s.split(separator: ":").map { Double($0) ?? 0 }
 98            return parts[0] * 60 + parts[1] + (parts.count > 2 ? parts[2] / 60 : 0)
 99        }
100        let unit = /([0-9]+(?:\.[0-9]*)?)[ \t]*(min|h|d|w|m|y)/
101        if s.wholeMatch(of: /(?:[0-9]+(?:\.[0-9]*)?[ \t]*(?:min|h|d|w|m|y)[ \t]*)+/) != nil {
102            var total = 0.0
103            for m in s.matches(of: unit) {
104                let name = String(m.2)
105                total += (Double(m.1) ?? 0) * (unitMinutes.first { $0.0 == name }?.1 ?? 0)
106            }
107            return total
108        }
109        if let m = s.wholeMatch(of: /((?:[0-9]+(?:\.[0-9]*)?[ \t]*(?:min|h|d|w|m|y)[ \t]*)+)[ \t]*([0-9]+(?::[0-9]{2}){1,2})/) {
110            return (minutes(String(m.1)) ?? 0) + (minutes(String(m.2)) ?? 0)
111        }
112        if s.wholeMatch(of: /[0-9]+(?:\.[0-9]*)?/) != nil { return Double(s) }
113        return nil
114    }
115
116    /// `org-duration-from-minutes` with `h:mm`, or with nil the default format (days, then
117    /// `H:MM`).
118    static func duration(_ minutes: Double, hmmOnly: Bool) -> String {
119        if minutes < 0 { return "-" + duration(-minutes, hmmOnly: hmmOnly) }
120        func hmm(_ m: Double) -> String { String(format: "%d:%02d", Int(m / 60), Int(m.truncatingRemainder(dividingBy: 60))) }
121        if hmmOnly || minutes < 1440 { return hmm(minutes) }
122        let days = (minutes / 1440).rounded(.down)
123        return "\(Int(days))d " + hmm(minutes - days * 1440)
124    }
125
126    /// `org-columns--age-to-minutes`: minutes since an active timestamp in `value`, or a duration.
127    static func ageMinutes(_ value: String, now: Date, calendar: Calendar) throws -> Double {
128        if let range = value.range(of: "<[0-9]{4}-[0-9]{2}-[0-9]{2}(?: .*?)?>", options: .regularExpression) {
129            guard let stamp = EmacsBuffer.parseTimeString(String(value[range])), let date = calendar.date(from: stamp) else {
130                throw EmacsBuffer.UserError(message: "Invalid age: \"\(value)\"")
131            }
132            return now.timeIntervalSince(date) / 60
133        }
134        guard !value.trimmingCharacters(in: .whitespaces).isEmpty, let minutes = minutes(value) else {
135            throw EmacsBuffer.UserError(message: "Invalid age: \"\(value)\"")
136        }
137        return minutes
138    }
139
140    /// `org-columns--format-age`: days, hours and minutes, those that aren't zero.
141    static func age(_ minutes: Double) -> String {
142        if minutes < 0 { return "-" + age(-minutes) }
143        var left = minutes
144        var parts: [String] = []
145        for (unit, modifier) in [("d", 1440.0), ("h", 60.0), ("min", 1.0)] where modifier <= left {
146            let value = (left / modifier).rounded(.down)
147            left -= value * modifier
148            parts.append("\(Int(value))\(unit)")
149        }
150        return parts.isEmpty ? "0min" : parts.joined(separator: " ")
151    }
152
153    /// `org-columns--summarize`: nil for an unknown operator.
154    static func summarize(_ op: String, _ values: [String], fmt: String?, now: Date, calendar: Calendar = .current) throws -> String? {
155        let numbers = values.map(Number.init)
156        switch op {
157        case "@min", "@max", "@mean":
158            let ages = try values.map { try ageMinutes($0, now: now, calendar: calendar) }
159            return age(op == "@min" ? ages.min()! : op == "@max" ? ages.max()! : ages.reduce(0, +) / Double(ages.count))
160        case "+": return format(fmt, numbers.reduce(.int(0), +))
161        case "$": return String(format: "%.2f", numbers.reduce(0) { $0 + $1.double })
162        case "X":
163            let done = values.filter { $0 == "[X]" }.count
164            return done == values.count ? "[X]" : done > 0 ? "[-]" : "[ ]"
165        case "X/":
166            let done = values.filter { $0 == "[X]" || $0.firstMatch(of: /\[([1-9])\/\1\]/) != nil }.count
167            return "[\(done)/\(values.count)]"
168        case "X%":
169            let done = values.filter { $0 == "[X]" || $0 == "[100%]" }.count
170            return "[\(Int((100.0 * Double(done) / Double(values.count)).rounded()))%]"
171        case "min", "max":
172            var best = numbers[0]
173            for n in numbers.dropFirst() where op == "min" ? n.double < best.double : n.double > best.double { best = n }
174            return format(fmt, best)
175        case "mean": return format(fmt, .float(numbers.reduce(0) { $0 + $1.double } / Double(numbers.count)))
176        case ":", ":min", ":max", ":mean":
177            let times = values.compactMap(minutes)
178            guard !times.isEmpty else { return nil }
179            let hmmOnly = values.allSatisfy { $0.trimmingCharacters(in: .whitespaces).wholeMatch(of: /[0-9]+(?::[0-9]{2}){1,2}/) != nil }
180            let result: Double = switch op {
181            case ":": times.reduce(0, +)
182            case ":min": times.min()!
183            case ":max": times.max()!
184            default: times.reduce(0, +) / Double(times.count)
185            }
186            return duration(result, hmmOnly: hmmOnly)
187        case "est+":
188            var mean = 0.0, variance = 0.0
189            for e in values {
190                let parts = e.split(separator: "-", omittingEmptySubsequences: false).map { Number(String($0)).double }
191                if parts.count == 2 {
192                    let m = (parts[0] + parts[1]) / 2
193                    mean += m
194                    variance += (parts[0] * parts[0] + parts[1] * parts[1]) / 2 - m * m
195                } else if let v = parts.first {
196                    mean += v
197                }
198            }
199            let sd = variance.squareRoot()
200            return String(format: "%.0f-%.0f", mean - sd, mean + sd)
201        default: return nil
202        }
203    }
204
205    // MARK: - Values
206
207    static let specials: Set<String> = PropertyValues.special.union(["CATEGORY"])
208
209    /// `org-entry-get` with `selective` inheritance, and the special properties column view
210    /// shows.
211    static func value(_ property: String, heading index: Int, model: DocumentModel, text: NSString, clocksum: [Int: Int]) -> String {
212        let h = model.headings[index]
213        switch property {
214        case "ITEM": return h.title.replacingOccurrences(of: "\t", with: "        ")
215        case "TODO": return h.todo ?? ""
216        case "PRIORITY": return h.priority ?? model.orgSettings.priorities.default
217        case "TAGS": return h.localTags.isEmpty ? "" : ":" + h.localTags.joined(separator: ":") + ":"
218        case "ALLTAGS":
219            let all = model.tags(of: index).map(\.value)
220            return all.isEmpty ? "" : ":" + all.joined(separator: ":") + ":"
221        case "DEADLINE", "SCHEDULED", "CLOSED":
222            // From the planning line under the heading.
223            let next = NSMaxRange(text.lineRange(for: NSRange(location: h.headingRange.lowerBound, length: 0)))
224            guard next < text.length else { return "" }
225            let line = text.substring(with: text.lineRange(for: NSRange(location: next, length: 0)))
226            guard line.range(of: "^[ \\t]*(?:SCHEDULED|DEADLINE|CLOSED):", options: .regularExpression) != nil,
227                  let m = line.range(of: property + ": *(<[^>\\n]+>|\\[[^\\]\\n]+\\])", options: .regularExpression) else { return "" }
228            return String(line[m]).replacingOccurrences(of: "^" + property + ": *", with: "", options: .regularExpression)
229        case "CLOCKSUM": return clocksum[index].map { ClockTable.duration($0) } ?? ""
230        default:
231            return model.property(property, of: index)?.value ?? ""
232        }
233    }
234
235    /// `org-columns--displayed-value` without the stars on ITEM.
236    static func displayed(_ spec: Spec, _ value: String) -> String {
237        switch spec.property {
238        case "ITEM": return value
239        case "DEADLINE", "SCHEDULED", "TIMESTAMP": return value.replacingOccurrences(of: "<([^>]*)>", with: "[$1]", options: .regularExpression)
240        default: return spec.format.map { format($0, Number(value)) } ?? value
241        }
242    }
243
244    // MARK: - The view
245
246    /// `org-columns` and `org-columns--capture-view` at `offset`: the format, the entries from the
247    /// top level (the first ancestor with COLUMNS, else the entry; the file before the first
248    /// heading or with `global`), their values with summaries. `updates` are the parents whose
249    /// summarized property org rewrites.
250    /// Throws for an age operator's value that is neither a timestamp nor a duration.
251    public static func capture(text: String, tree: OrgTree, at offset: Int, global: Bool, format override: String? = nil,
252                               maxLevel: Int? = nil, skipEmpty: Bool = false, excludeTags: [String] = [], now: Date = Date(),
253                               calendar: Calendar = .current) throws
254        -> (view: View, updates: [(start: Int, property: String, value: String)]) {
255        let model = DocumentModel(tree: tree)
256        let ns = text as NSString
257        let headings = model.headings
258        let here = global ? nil : headings.lastIndex { $0.headingRange.lowerBound <= offset }
259        // The top level and the format.
260        var top: Int?
261        var format = override
262        if let here {
263            for h in [here] + model.ancestors(of: here).reversed() {
264                if let columns = headings[h].properties.last(where: { $0.key.uppercased() == "COLUMNS" }) {
265                    top = h
266                    if format == nil { format = columns.value }
267                    break
268                }
269            }
270            if top == nil { top = here }
271        }
272        if format == nil, let keyword = (tree.settings.setupKeywords + text).firstMatch(of: #/(?mi)^[ \t]*#\+COLUMNS:[ \t]+(.+?)[ \t]*$/#) { format = String(keyword.1) }
273        let specs = compile(format ?? defaultFormat)
274        // The entries in scope, without archived or commented subtrees.
275        var scope: [Int] = []
276        let end: Int = top.map { t in headings[(t + 1)...].firstIndex { $0.level <= headings[t].level } ?? headings.count } ?? headings.count
277        var skipBelow: Int?
278        for i in (top ?? 0)..<end {
279            if let level = skipBelow, headings[i].level > level { continue }
280            skipBelow = nil
281            let title = headings[i].title
282            if headings[i].localTags.contains("ARCHIVE") || title == "COMMENT" || title.hasPrefix("COMMENT ") {
283                skipBelow = headings[i].level
284                continue
285            }
286            scope.append(i)
287        }
288        // Clocked minutes per subtree, as `org-clock-sum`.
289        var clocksum: [Int: Int] = [:]
290        if specs.contains(where: { $0.property == "CLOCKSUM" }) {
291            for i in headings.indices {
292                let own = headings[i].clocks.compactMap(\.minutes).reduce(0, +)
293                guard own > 0 else { continue }
294                for h in [i] + model.ancestors(of: i) { clocksum[h, default: 0] += own }
295            }
296        }
297        // Summaries, bottom up through the whole top-level subtree.
298        var summaries: [Int: [Int: String]] = [:]
299        var updates: [(Int, String, String)] = []
300        var seen: Set<String> = []
301        for (column, spec) in specs.enumerated() {
302            let first = seen.insert(spec.property).inserted
303            guard let op = spec.summary, !PropertyValues.special.contains(spec.property) else { continue }
304            var accumulators = [[String]](repeating: [], count: 31)
305            var level = 0
306            var lastLevel = 30
307            for i in ((top ?? 0)..<end).reversed() {
308                if level != 0 { lastLevel = level }
309                level = min(30, headings[i].level)
310                let own = headings[i].properties.last { $0.key.uppercased() == spec.property }?.value
311                let set = own.map { $0.contains { !$0.isWhitespace } } ?? false
312                if level < lastLevel {
313                    let below = accumulators[(level + 1)...].flatMap { $0 }
314                    let summary = below.isEmpty ? nil : try summarize(op, below, fmt: spec.format, now: now, calendar: calendar)
315                    if let summary {
316                        summaries[i, default: [:]][column] = summary
317                        let trimmed = summary.trimmingCharacters(in: .whitespaces)
318                        if first, let own, own != trimmed { updates.append((headings[i].headingRange.lowerBound, spec.property, trimmed)) }
319                    }
320                    if let value = summary ?? (set ? own : nil) { accumulators[level].append(value) }
321                    for l in (level + 1)...30 { accumulators[l] = [] }
322                } else if set, let own {
323                    accumulators[level].append(own)
324                }
325            }
326        }
327        // Rows.
328        var rows: [Row] = []
329        for i in scope {
330            let level = headings[i].level
331            if let maxLevel, level > maxLevel { continue }
332            let values = specs.enumerated().map { column, spec -> String in
333                let raw = summaries[i]?[column] ?? value(spec.property, heading: i, model: model, text: ns, clocksum: clocksum)
334                return displayed(spec, raw)
335            }
336            if skipEmpty {
337                let others = Set(zip(specs, values).filter { $0.0.property != "ITEM" }.map(\.1)).subtracting([""])
338                if others.isEmpty { continue }
339            }
340            if !excludeTags.isEmpty {
341                let tags = model.tags(of: i).map(\.value)
342                if tags.contains(where: excludeTags.contains) { continue }
343            }
344            rows.append(Row(level: level, start: headings[i].headingRange.lowerBound, values: values))
345        }
346        return (View(specs: specs, rows: rows), updates)
347    }
348
349    /// `org-columns--clean-item`: no footnote references, targets, statistics cookies or inline
350    /// source blocks, and `|` as `\vert`.
351    static func cleanItem(_ item: String) -> String {
352        var s = item
353        s = s.replacingOccurrences(of: "\\[fn:[^\\]]*\\]", with: "", options: .regularExpression)
354        s = s.replacingOccurrences(of: "<<<?([^<>]*)>>>?", with: "", options: .regularExpression)
355        s = s.replacingOccurrences(of: "\\[[0-9]*(?:%|/[0-9]*)\\]", with: "", options: .regularExpression)
356        s = s.replacingOccurrences(of: "src_[^\\s{\\[]+(?:\\[[^\\]]*\\])?\\{[^}]*\\}", with: "", options: .regularExpression)
357        return s.trimmingCharacters(in: .whitespaces).replacingOccurrences(of: "|", with: "\\vert")
358    }
359
360    /// `org-columns-dblock-write-default`'s rows, before alignment.
361    static func dblockTable(_ view: View, hlines: Int?, hlinesAll: Bool, indent: Bool) -> [[String]?] {
362        var table: [[String]?] = [view.specs.map(\.title), nil]
363        let item = view.specs.firstIndex { $0.property == "ITEM" }
364        for row in view.rows {
365            if table.last! != nil, hlinesAll || hlines.map({ row.level <= $0 }) == true { table.append(nil) }
366            var values = row.values
367            if let item {
368                let cleaned = cleanItem(values[item])
369                values[item] = indent && row.level > 1 ? "\\_" + String(repeating: " ", count: 2 * (row.level - 1)) + cleaned : cleaned
370            }
371            table.append(values)
372        }
373        if view.specs.contains(where: { $0.width != nil }) {
374            table.insert(view.specs.map { $0.width.map { "<\($0)>" } ?? "" }, at: 0)
375        }
376        return table
377    }
378}
379
380extension EmacsBuffer {
381    /// `org-dblock-write:columnview` and the default writer, at point (the line after #+BEGIN).
382    func writeColumnView(_ params: ClockTable.Params, at begin: Int, content: String, tree: OrgTree) throws -> String {
383        let id = params.values[":id"]
384        var offset = begin
385        var global = false
386        if let id {
387            switch id.symbol ?? id.string ?? "" {
388            case "global": global = true
389            case "local", "nil", "": break
390            case let value:
391                if value.hasPrefix("file:") { throw UserError(message: "Column views of other files aren't supported yet") }
392                guard let match = searchForwardFromStart("^[ \\t]*:ID:[ \\t]+" + NSRegularExpression.escapedPattern(for: value) + "[ \\t]*$") else {
393                    throw UserError(message: "Cannot find entry with :ID: \(value)")
394                }
395                offset = match
396            }
397        }
398        let hlines = params.values[":hlines"]
399        let excluded = params.values[":exclude-tags"]?.elements?.compactMap { $0.string ?? $0.symbol } ?? []
400        let captured = try ColumnView.capture(text: string, tree: tree, at: offset, global: global, format: params.values[":format"]?.string,
401                                              maxLevel: params.int(":maxlevel"), skipEmpty: params.flag(":skip-empty-rows"),
402                                              excludeTags: excluded, now: now, calendar: calendar)
403        for update in captured.updates.sorted(by: { $0.start > $1.start }) {
404            point = update.start
405            entryPut(update.property, update.value)
406        }
407        let table = ColumnView.dblockTable(captured.view, hlines: hlines?.integer, hlinesAll: hlines?.symbol == "t",
408                                           indent: params.flag(":indent"))
409        var lines = table.map { row in row.map { "|" + $0.joined(separator: "|") + "|" } ?? "|-|" }
410        for line in content.split(separator: "\n") where line.range(of: "^[ \\t]*#\\+TBLFM:", options: [.regularExpression, .caseInsensitive]) != nil {
411            lines.append(line.trimmingCharacters(in: .whitespaces))
412        }
413        return lines.joined(separator: "\n")
414    }
415
416    private func searchForwardFromStart(_ pattern: String) -> Int? {
417        saveExcursion {
418            point = 0
419            return searchForward(pattern, caseInsensitive: true)?[0]?.lowerBound
420        }
421    }
422}