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