Sources/OrgCore/Commands/ColumnView.swift
424 lines · 21791 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 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 tags = model.ancestors(of: index).flatMap { model.headings[$0].localTags } + h.localTags
220 var seen: Set<String> = []
221 let all = (model.fileTags + tags).filter { seen.insert($0).inserted }
222 return all.isEmpty ? "" : ":" + all.joined(separator: ":") + ":"
223 case "DEADLINE", "SCHEDULED", "CLOSED":
224 // From the planning line under the heading.
225 let next = NSMaxRange(text.lineRange(for: NSRange(location: h.headingRange.lowerBound, length: 0)))
226 guard next < text.length else { return "" }
227 let line = text.substring(with: text.lineRange(for: NSRange(location: next, length: 0)))
228 guard line.range(of: "^[ \\t]*(?:SCHEDULED|DEADLINE|CLOSED):", options: .regularExpression) != nil,
229 let m = line.range(of: property + ": *(<[^>\\n]+>|\\[[^\\]\\n]+\\])", options: .regularExpression) else { return "" }
230 return String(line[m]).replacingOccurrences(of: "^" + property + ": *", with: "", options: .regularExpression)
231 case "CLOCKSUM": return clocksum[index].map { ClockTable.duration($0) } ?? ""
232 default:
233 return model.property(property, of: index)?.value ?? ""
234 }
235 }
236
237 /// `org-columns--displayed-value` without the stars on ITEM.
238 static func displayed(_ spec: Spec, _ value: String) -> String {
239 switch spec.property {
240 case "ITEM": return value
241 case "DEADLINE", "SCHEDULED", "TIMESTAMP": return value.replacingOccurrences(of: "<([^>]*)>", with: "[$1]", options: .regularExpression)
242 default: return spec.format.map { format($0, Number(value)) } ?? value
243 }
244 }
245
246 // MARK: - The view
247
248 /// `org-columns` and `org-columns--capture-view` at `offset`: the format, the entries from the
249 /// top level (the first ancestor with COLUMNS, else the entry; the file before the first
250 /// heading or with `global`), their values with summaries. `updates` are the parents whose
251 /// summarized property org rewrites.
252 /// Throws for an age operator's value that is neither a timestamp nor a duration.
253 public static func capture(text: String, tree: OrgTree, at offset: Int, global: Bool, format override: String? = nil,
254 maxLevel: Int? = nil, skipEmpty: Bool = false, excludeTags: [String] = [], now: Date = Date(),
255 calendar: Calendar = .current) throws
256 -> (view: View, updates: [(start: Int, property: String, value: String)]) {
257 let model = DocumentModel(tree: tree)
258 let ns = text as NSString
259 let headings = model.headings
260 let here = global ? nil : headings.lastIndex { $0.headingRange.lowerBound <= offset }
261 // The top level and the format.
262 var top: Int?
263 var format = override
264 if let here {
265 for h in [here] + model.ancestors(of: here).reversed() {
266 if let columns = headings[h].properties.last(where: { $0.key.uppercased() == "COLUMNS" }) {
267 top = h
268 if format == nil { format = columns.value }
269 break
270 }
271 }
272 if top == nil { top = here }
273 }
274 if format == nil, let keyword = (tree.settings.setupKeywords + text).firstMatch(of: #/(?mi)^[ \t]*#\+COLUMNS:[ \t]+(.+?)[ \t]*$/#) { format = String(keyword.1) }
275 let specs = compile(format ?? defaultFormat)
276 // The entries in scope, without archived or commented subtrees.
277 var scope: [Int] = []
278 let end: Int = top.map { t in headings[(t + 1)...].firstIndex { $0.level <= headings[t].level } ?? headings.count } ?? headings.count
279 var skipBelow: Int?
280 for i in (top ?? 0)..<end {
281 if let level = skipBelow, headings[i].level > level { continue }
282 skipBelow = nil
283 let title = headings[i].title
284 if headings[i].localTags.contains("ARCHIVE") || title == "COMMENT" || title.hasPrefix("COMMENT ") {
285 skipBelow = headings[i].level
286 continue
287 }
288 scope.append(i)
289 }
290 // Clocked minutes per subtree, as `org-clock-sum`.
291 var clocksum: [Int: Int] = [:]
292 if specs.contains(where: { $0.property == "CLOCKSUM" }) {
293 for i in headings.indices {
294 let own = headings[i].clocks.compactMap(\.minutes).reduce(0, +)
295 guard own > 0 else { continue }
296 for h in [i] + model.ancestors(of: i) { clocksum[h, default: 0] += own }
297 }
298 }
299 // Summaries, bottom up through the whole top-level subtree.
300 var summaries: [Int: [Int: String]] = [:]
301 var updates: [(Int, String, String)] = []
302 var seen: Set<String> = []
303 for (column, spec) in specs.enumerated() {
304 let first = seen.insert(spec.property).inserted
305 guard let op = spec.summary, !PropertyValues.special.contains(spec.property) else { continue }
306 var accumulators = [[String]](repeating: [], count: 31)
307 var level = 0
308 var lastLevel = 30
309 for i in ((top ?? 0)..<end).reversed() {
310 if level != 0 { lastLevel = level }
311 level = min(30, headings[i].level)
312 let own = headings[i].properties.last { $0.key.uppercased() == spec.property }?.value
313 let set = own.map { $0.contains { !$0.isWhitespace } } ?? false
314 if level < lastLevel {
315 let below = accumulators[(level + 1)...].flatMap { $0 }
316 let summary = below.isEmpty ? nil : try summarize(op, below, fmt: spec.format, now: now, calendar: calendar)
317 if let summary {
318 summaries[i, default: [:]][column] = summary
319 let trimmed = summary.trimmingCharacters(in: .whitespaces)
320 if first, let own, own != trimmed { updates.append((headings[i].headingRange.lowerBound, spec.property, trimmed)) }
321 }
322 if let value = summary ?? (set ? own : nil) { accumulators[level].append(value) }
323 for l in (level + 1)...30 { accumulators[l] = [] }
324 } else if set, let own {
325 accumulators[level].append(own)
326 }
327 }
328 }
329 // Rows.
330 var rows: [Row] = []
331 for i in scope {
332 let level = headings[i].level
333 if let maxLevel, level > maxLevel { continue }
334 let values = specs.enumerated().map { column, spec -> String in
335 let raw = summaries[i]?[column] ?? value(spec.property, heading: i, model: model, text: ns, clocksum: clocksum)
336 return displayed(spec, raw)
337 }
338 if skipEmpty {
339 let others = Set(zip(specs, values).filter { $0.0.property != "ITEM" }.map(\.1)).subtracting([""])
340 if others.isEmpty { continue }
341 }
342 if !excludeTags.isEmpty {
343 let tags = model.ancestors(of: i).flatMap { headings[$0].localTags } + headings[i].localTags + model.fileTags
344 if tags.contains(where: excludeTags.contains) { continue }
345 }
346 rows.append(Row(level: level, start: headings[i].headingRange.lowerBound, values: values))
347 }
348 return (View(specs: specs, rows: rows), updates)
349 }
350
351 /// `org-columns--clean-item`: no footnote references, targets, statistics cookies or inline
352 /// source blocks, and `|` as `\vert`.
353 static func cleanItem(_ item: String) -> String {
354 var s = item
355 s = s.replacingOccurrences(of: "\\[fn:[^\\]]*\\]", with: "", options: .regularExpression)
356 s = s.replacingOccurrences(of: "<<<?([^<>]*)>>>?", with: "", options: .regularExpression)
357 s = s.replacingOccurrences(of: "\\[[0-9]*(?:%|/[0-9]*)\\]", with: "", options: .regularExpression)
358 s = s.replacingOccurrences(of: "src_[^\\s{\\[]+(?:\\[[^\\]]*\\])?\\{[^}]*\\}", with: "", options: .regularExpression)
359 return s.trimmingCharacters(in: .whitespaces).replacingOccurrences(of: "|", with: "\\vert")
360 }
361
362 /// `org-columns-dblock-write-default`'s rows, before alignment.
363 static func dblockTable(_ view: View, hlines: Int?, hlinesAll: Bool, indent: Bool) -> [[String]?] {
364 var table: [[String]?] = [view.specs.map(\.title), nil]
365 let item = view.specs.firstIndex { $0.property == "ITEM" }
366 for row in view.rows {
367 if table.last! != nil, hlinesAll || hlines.map({ row.level <= $0 }) == true { table.append(nil) }
368 var values = row.values
369 if let item {
370 let cleaned = cleanItem(values[item])
371 values[item] = indent && row.level > 1 ? "\\_" + String(repeating: " ", count: 2 * (row.level - 1)) + cleaned : cleaned
372 }
373 table.append(values)
374 }
375 if view.specs.contains(where: { $0.width != nil }) {
376 table.insert(view.specs.map { $0.width.map { "<\($0)>" } ?? "" }, at: 0)
377 }
378 return table
379 }
380}
381
382extension EmacsBuffer {
383 /// `org-dblock-write:columnview` and the default writer, at point (the line after #+BEGIN).
384 func writeColumnView(_ params: ClockTable.Params, at begin: Int, content: String, tree: OrgTree) throws -> String {
385 let id = params.values[":id"]
386 var offset = begin
387 var global = false
388 if let id {
389 switch id.symbol ?? id.string ?? "" {
390 case "global": global = true
391 case "local", "nil", "": break
392 case let value:
393 if value.hasPrefix("file:") { throw UserError(message: "Column views of other files aren't supported yet") }
394 guard let match = searchForwardFromStart("^[ \\t]*:ID:[ \\t]+" + NSRegularExpression.escapedPattern(for: value) + "[ \\t]*$") else {
395 throw UserError(message: "Cannot find entry with :ID: \(value)")
396 }
397 offset = match
398 }
399 }
400 let hlines = params.values[":hlines"]
401 let excluded = params.values[":exclude-tags"]?.elements?.compactMap { $0.string ?? $0.symbol } ?? []
402 let captured = try ColumnView.capture(text: string, tree: tree, at: offset, global: global, format: params.values[":format"]?.string,
403 maxLevel: params.int(":maxlevel"), skipEmpty: params.flag(":skip-empty-rows"),
404 excludeTags: excluded, now: now, calendar: calendar)
405 for update in captured.updates.sorted(by: { $0.start > $1.start }) {
406 point = update.start
407 entryPut(update.property, update.value)
408 }
409 let table = ColumnView.dblockTable(captured.view, hlines: hlines?.integer, hlinesAll: hlines?.symbol == "t",
410 indent: params.flag(":indent"))
411 var lines = table.map { row in row.map { "|" + $0.joined(separator: "|") + "|" } ?? "|-|" }
412 for line in content.split(separator: "\n") where line.range(of: "^[ \\t]*#\\+TBLFM:", options: [.regularExpression, .caseInsensitive]) != nil {
413 lines.append(line.trimmingCharacters(in: .whitespaces))
414 }
415 return lines.joined(separator: "\n")
416 }
417
418 private func searchForwardFromStart(_ pattern: String) -> Int? {
419 saveExcursion {
420 point = 0
421 return searchForward(pattern, caseInsensitive: true)?[0]?.lowerBound
422 }
423 }
424}