Column view: @min, @max and @mean !251
5 files changed, +107 −10
Layout: unified · split
Sources/OrgCore/Commands/ClockTable.swift +8 −1
| @@ -475,7 +475,14 @@ public struct ShowColumnView: OrgCommand { | |||
| 475 | public var title: String { global ? "Column View of File" : "Column View" } | 475 | public var title: String { global ? "Column View of File" : "Column View" } |
| 476 | public func applies(in context: EditContext) -> Bool { true } | 476 | public func applies(in context: EditContext) -> Bool { true } |
| 477 | public func run(in context: EditContext) -> CommandStep { | 477 | public func run(in context: EditContext) -> CommandStep { |
| 478 | let view = ColumnView.capture(text: context.text, tree: context.tree, at: context.caret, global: global, now: context.now).view | 478 | let view: ColumnView.View |
| 479 | do { | ||
| 480 | view = try ColumnView.capture(text: context.text, tree: context.tree, at: context.caret, global: global, now: context.now, calendar: context.calendar).view | ||
| 481 | } catch let error as EmacsBuffer.UserError { | ||
| 482 | return .failed(error.message) | ||
| 483 | } catch { | ||
| 484 | return .failed("\(error)") | ||
| 485 | } | ||
| 479 | guard !view.rows.isEmpty else { return .failed("No entries for column view") } | 486 | guard !view.rows.isEmpty else { return .failed("No entries for column view") } |
| 480 | return .external(.columnView(view)) | 487 | return .external(.columnView(view)) |
| 481 | } | 488 | } |
Sources/OrgCore/Commands/ColumnView.swift +38 −6
| @@ -123,10 +123,40 @@ public enum ColumnView { | |||
| 123 | return "\(Int(days))d " + hmm(minutes - days * 1440) | 123 | return "\(Int(days))d " + hmm(minutes - days * 1440) |
| 124 | } | 124 | } |
| 125 | 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 | |||
| 126 | /// `org-columns--summarize`: nil for an unknown operator. | 153 | /// `org-columns--summarize`: nil for an unknown operator. |
| 127 | static func summarize(_ op: String, _ values: [String], fmt: String?, now: Date) -> String? { | 154 | static func summarize(_ op: String, _ values: [String], fmt: String?, now: Date, calendar: Calendar = .current) throws -> String? { |
| 128 | let numbers = values.map(Number.init) | 155 | let numbers = values.map(Number.init) |
| 129 | switch op { | 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)) | ||
| 130 | case "+": return format(fmt, numbers.reduce(.int(0), +)) | 160 | case "+": return format(fmt, numbers.reduce(.int(0), +)) |
| 131 | case "$": return String(format: "%.2f", numbers.reduce(0) { $0 + $1.double }) | 161 | case "$": return String(format: "%.2f", numbers.reduce(0) { $0 + $1.double }) |
| 132 | case "X": | 162 | case "X": |
| @@ -219,8 +249,10 @@ public enum ColumnView { | |||
| 219 | /// top level (the first ancestor with COLUMNS, else the entry; the file before the first | 249 | /// top level (the first ancestor with COLUMNS, else the entry; the file before the first |
| 220 | /// heading or with `global`), their values with summaries. `updates` are the parents whose | 250 | /// heading or with `global`), their values with summaries. `updates` are the parents whose |
| 221 | /// summarized property org rewrites. | 251 | /// summarized property org rewrites. |
| 252 | /// Throws for an age operator's value that is neither a timestamp nor a duration. | ||
| 222 | public static func capture(text: String, tree: OrgTree, at offset: Int, global: Bool, format override: String? = nil, | 253 | public static func capture(text: String, tree: OrgTree, at offset: Int, global: Bool, format override: String? = nil, |
| 223 | maxLevel: Int? = nil, skipEmpty: Bool = false, excludeTags: [String] = [], now: Date = Date()) | 254 | maxLevel: Int? = nil, skipEmpty: Bool = false, excludeTags: [String] = [], now: Date = Date(), |
| 255 | calendar: Calendar = .current) throws | ||
| 224 | -> (view: View, updates: [(start: Int, property: String, value: String)]) { | 256 | -> (view: View, updates: [(start: Int, property: String, value: String)]) { |
| 225 | let model = DocumentModel(tree: tree) | 257 | let model = DocumentModel(tree: tree) |
| 226 | let ns = text as NSString | 258 | let ns = text as NSString |
| @@ -281,7 +313,7 @@ public enum ColumnView { | |||
| 281 | let set = own.map { $0.contains { !$0.isWhitespace } } ?? false | 313 | let set = own.map { $0.contains { !$0.isWhitespace } } ?? false |
| 282 | if level < lastLevel { | 314 | if level < lastLevel { |
| 283 | let below = accumulators[(level + 1)...].flatMap { $0 } | 315 | let below = accumulators[(level + 1)...].flatMap { $0 } |
| 284 | let summary = below.isEmpty ? nil : summarize(op, below, fmt: spec.format, now: now) | 316 | let summary = below.isEmpty ? nil : try summarize(op, below, fmt: spec.format, now: now, calendar: calendar) |
| 285 | if let summary { | 317 | if let summary { |
| 286 | summaries[i, default: [:]][column] = summary | 318 | summaries[i, default: [:]][column] = summary |
| 287 | let trimmed = summary.trimmingCharacters(in: .whitespaces) | 319 | let trimmed = summary.trimmingCharacters(in: .whitespaces) |
| @@ -367,9 +399,9 @@ extension EmacsBuffer { | |||
| 367 | } | 399 | } |
| 368 | let hlines = params.values[":hlines"] | 400 | let hlines = params.values[":hlines"] |
| 369 | let excluded = params.values[":exclude-tags"]?.elements?.compactMap { $0.string ?? $0.symbol } ?? [] | 401 | let excluded = params.values[":exclude-tags"]?.elements?.compactMap { $0.string ?? $0.symbol } ?? [] |
| 370 | let captured = ColumnView.capture(text: string, tree: tree, at: offset, global: global, format: params.values[":format"]?.string, | 402 | let captured = try ColumnView.capture(text: string, tree: tree, at: offset, global: global, format: params.values[":format"]?.string, |
| 371 | maxLevel: params.int(":maxlevel"), skipEmpty: params.flag(":skip-empty-rows"), | 403 | maxLevel: params.int(":maxlevel"), skipEmpty: params.flag(":skip-empty-rows"), |
| 372 | excludeTags: excluded, now: now) | 404 | excludeTags: excluded, now: now, calendar: calendar) |
| 373 | for update in captured.updates.sorted(by: { $0.start > $1.start }) { | 405 | for update in captured.updates.sorted(by: { $0.start > $1.start }) { |
| 374 | point = update.start | 406 | point = update.start |
| 375 | entryPut(update.property, update.value) | 407 | entryPut(update.property, update.value) |
Sources/Orgstar/InspectorPane.swift +1 −1
| @@ -127,7 +127,7 @@ struct InspectorPane: View { | |||
| 127 | return | 127 | return |
| 128 | } | 128 | } |
| 129 | let text = document.text | 129 | let text = document.text |
| 130 | columns = ColumnView.capture(text: text, tree: document.tree, at: heading ?? 0, global: !subtree || heading == nil).view | 130 | columns = (try? ColumnView.capture(text: text, tree: document.tree, at: heading ?? 0, global: !subtree || heading == nil))?.view |
| 131 | let formatter = DateFormatter() | 131 | let formatter = DateFormatter() |
| 132 | formatter.locale = Locale(identifier: "en_US_POSIX") | 132 | formatter.locale = Locale(identifier: "en_US_POSIX") |
| 133 | formatter.dateFormat = "yyyy-MM-dd" | 133 | formatter.dateFormat = "yyyy-MM-dd" |
Tests/OrgCoreTests/ColumnViewTests.swift +56
| @@ -77,6 +77,62 @@ struct ColumnViewTests { | |||
| 77 | } | 77 | } |
| 78 | } | 78 | } |
| 79 | 79 | ||
| 80 | /// `@min`, `@max` and `@mean` over timestamps and durations, at a fixed time. | ||
| 81 | @Test(.enabled(if: oracle)) | ||
| 82 | func summarizesAgesLikeOrg() throws { | ||
| 83 | let seconds = 1_789_000_000 | ||
| 84 | let texts = [ | ||
| 85 | """ | ||
| 86 | * Ages | ||
| 87 | :PROPERTIES: | ||
| 88 | :COLUMNS: %ITEM %Seen{@min} %Seen{@max} %Seen{@mean} | ||
| 89 | :END: | ||
| 90 | #+BEGIN: columnview :id local | ||
| 91 | #+END: | ||
| 92 | ** A | ||
| 93 | :PROPERTIES: | ||
| 94 | :Seen: <2026-09-01 Tue> | ||
| 95 | :END: | ||
| 96 | ** B | ||
| 97 | :PROPERTIES: | ||
| 98 | :Seen: <2026-09-08 Tue 13:30> | ||
| 99 | :END: | ||
| 100 | ** C | ||
| 101 | :PROPERTIES: | ||
| 102 | :Seen: 3d 2h | ||
| 103 | :END: | ||
| 104 | *** D | ||
| 105 | :PROPERTIES: | ||
| 106 | :Seen: 45min | ||
| 107 | :END: | ||
| 108 | |||
| 109 | """, | ||
| 110 | "* P\n:PROPERTIES:\n:COLUMNS: %ITEM %Seen{@max}\n:END:\n#+BEGIN: columnview :id local\n#+END:\n** A\n:PROPERTIES:\n:Seen: [2026-09-01 Tue]\n:END:\n", | ||
| 111 | ] | ||
| 112 | var utc = Calendar(identifier: .gregorian) | ||
| 113 | utc.timeZone = TimeZone(identifier: "UTC")! | ||
| 114 | let cases = texts.map { text in | ||
| 115 | EmacsOracle.Case(text: text, point: EmacsOracle.point((text as NSString).range(of: "#+BEGIN").location, in: text), | ||
| 116 | form: frozenClock(seconds, "(org-update-dblock)")) | ||
| 117 | } | ||
| 118 | let emacs = try EmacsOracle.run(cases) | ||
| 119 | for (i, text) in texts.enumerated() { | ||
| 120 | let caret = (text as NSString).range(of: "#+BEGIN").location | ||
| 121 | let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret], | ||
| 122 | now: Date(timeIntervalSince1970: Double(seconds)), calendar: utc) | ||
| 123 | var ours = text | ||
| 124 | var failure = "" | ||
| 125 | switch UpdateDynamicBlock().run(in: context) { | ||
| 126 | case .commit(let result): ours = result.edits.sorted { $0.range.lowerBound > $1.range.lowerBound }.reduce(text) { $1.apply(to: $0) } | ||
| 127 | case .failed(let message): failure = message | ||
| 128 | default: break | ||
| 129 | } | ||
| 130 | // On an invalid age Org stops after emptying the block; orgstar leaves it as it was. | ||
| 131 | #expect(failure.isEmpty ? ours == emacs[i].text : emacs[i].error.contains(failure) && ours == text, | ||
| 132 | "ours:\n\(ours)\n\(failure)\nemacs:\n\(emacs[i].text)\n\(emacs[i].error)") | ||
| 133 | } | ||
| 134 | } | ||
| 135 | |||
| 80 | @Test func compilesFormats() { | 136 | @Test func compilesFormats() { |
| 81 | let specs = ColumnView.compile("%25ITEM(Task) %Effort{:} %3PRIORITY %Cost{+;%.2f}") | 137 | let specs = ColumnView.compile("%25ITEM(Task) %Effort{:} %3PRIORITY %Cost{+;%.2f}") |
| 82 | #expect(specs.map(\.property) == ["ITEM", "EFFORT", "PRIORITY", "COST"]) | 138 | #expect(specs.map(\.property) == ["ITEM", "EFFORT", "PRIORITY", "COST"]) |
docs/manual/guide/04-outlines.org +4 −2
| @@ -629,8 +629,10 @@ Column view shows entries as rows and properties as columns. The columns come fr | |||
| 629 | Each column is =%[width]PROPERTY[(title)][{summary}]=, as in Org. The width limits the | 629 | Each column is =%[width]PROPERTY[(title)][{summary}]=, as in Org. The width limits the |
| 630 | column, the title replaces the property name in the header, and the summary is computed | 630 | column, the title replaces the property name in the header, and the summary is computed |
| 631 | for parent entries from their children. The summary operators are =+=, =$=, =min=, | 631 | for parent entries from their children. The summary operators are =+=, =$=, =min=, |
| 632 | =max=, =mean=, =X=, =X/=, =X%=, =:=, =:min=, =:max=, =:mean= and =est+=. Org's age | 632 | =max=, =mean=, =X=, =X/=, =X%=, =:=, =:min=, =:max=, =:mean=, =est+=, =@min=, =@max= |
| 633 | operators (=@min=, =@max=, =@mean=) are not supported. The numeric operators take a | 633 | and =@mean=. The age operators take an active timestamp, as its age now, or a duration, |
| 634 | and show the youngest, oldest or mean age in days, hours and minutes (=3d 2h 15min=); | ||
| 635 | any other value stops the view with "Invalid age". The numeric operators take a | ||
| 634 | format after a semicolon, as in ={+;%.1f}=. | 636 | format after a semicolon, as in ={+;%.1f}=. |
| 635 | 637 | ||
| 636 | Subtrees tagged =ARCHIVE= and commented subtrees are left out. | 638 | Subtrees tagged =ARCHIVE= and commented subtrees are left out. |